Home  >  Article  >  Web Front-end  >  Understand the use of NodeList, HTMLCollection and NamedNodeMap (code)

Understand the use of NodeList, HTMLCollection and NamedNodeMap (code)

云罗郡主
云罗郡主forward
2018-10-17 14:53:042029browse

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.

  1. HTMLCollection only contains element nodes, while NodeList contains any node type.

  2. 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.

  3. 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.

  4. 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(&#39;a1&#39;))
	console.log(res.namedItem(&#39;a2&#39;))
	// 结果如下图所示:
</script>

Understand the use of NodeList, HTMLCollection and NamedNodeMap (code)

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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete