Home >Web Front-end >JS Tutorial >Does JavaScript have collections?

Does JavaScript have collections?

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-07-16 11:43:372667browse

There are collections in JavaScript. The HTMLCollection object in JavaScript is an array-like list (collection) of HTML elements. The getElementsByTagName() method returns an HTMLCollection object.

Does JavaScript have collections?

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

There are collections in JavaScript. The HTMLCollection object in JavaScript is an array-like list (collection) of HTML elements. The getElementsByTagName() method returns an HTMLCollection object.

DOM collection in JavaScript:

The length attribute defines the number of elements in the HTMLCollection:

Example:

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript HTML DOM</h1>

<p>Hello World!</p>

<p>Hello China!</p>

<p id="demo"></p>

<script>
var myCollection = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = 
"此文档包含 " + myCollection.length + " 段文字。";
</script>

</body>
</html>

Effect:

Does JavaScript have collections?

Explanation of examples:

Create a collection of all

elements

Display the length of the collection

Note:

HTMLCollection is not an array!

HTMLCollection may look like an array, but it is not an array.

You can iterate over a list and reference elements numerically (just like an array).

However, you cannot use array methods such as valueOf(), pop(), push(), or join() on HTMLCollection.

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of Does JavaScript have collections?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn