Home > Article > Web Front-end > Understand the use of NodeList, HTMLCollection and NamedNodeMap (code)
The content of this article is about understanding the use (code) of NodeList, HTMLCollection and NamedNodeMap. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
These three are array-like objects.
HTMLCollection only contains element nodes, while NodeList contains any node type.
The HTMLCollection object can call the item() and namedItem() methods, and the NodeList object can only call the item() method. When getting elements, both can be done through the square bracket syntax or the item() method. The HTMLCollection object allows you to obtain elements by passing in a name or id through the namedItem() method.
Methods in some older browsers (such as getElementsByClassName()) return NodeList objects instead of HTMLCollection objects. The childNodes property of all browsers returns a NodeList object. Most browsers' querySelectorAll() returns a NodeList object. getElementsByTagName() returns an HTMLCollection object.
The NamedNodeMap object is obtained through the node.attributes attribute, and a pseudo array object composed of all attributes of the element is obtained.
Example:
<body> <p> <a href="#" id="a1">1</a> <a href="a.html" name="a2">2</a> </p> </body> <script> // 获取一个HTMLCollection对象 var res = document.getElementsByTagName("a"); console.log(res); console.log(res.item(0)) console.log(res[0]) console.log(res.namedItem('a1')) console.log(res.namedItem('a2')) // 结果如下图所示: </script>
The above is a complete introduction to the use (code) of NodeList, HTMLCollection and NamedNodeMap. If you If you want to know more about HTML video tutorial, please pay attention to the PHP Chinese website.
The above is the detailed content of Understand the use of NodeList, HTMLCollection and NamedNodeMap (code). For more information, please follow other related articles on the PHP Chinese website!