Home >Web Front-end >JS Tutorial >Does JavaScript have collections?
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.
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:
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!