Previously, child elements could be traversed using the childNodes property or firstChild, but it was necessary to determine whether the child element was an ELement element. Later, W3C defined a new set of attributes for traversal through the Element Traversal specification, which eliminates the need for judgment and is very convenient. 1. ChildNodes attribute traversal Child elements are usually traversed through the Please see the following code example: <div class="article"> <p>Paragraph 1</p> <p>Paragraph 2</p> <p>Paragraph Three</p> </div> <script type="text/javascript"> let childList = document.querySelector(".article").childNodes; console.log(childList); // Console output: // NodeList(7) 1 </script> Console view effect: Traverse the child element blank node: The obtained child elements contain blank If you want to traverse the p element in Then you need to determine whether the child element is of type Element: let childList = document.querySelector(".article").childNodes; // Traverse the child elements childList.forEach((item, index) => { if (item.nodeType == 1) { // Check if it is of Element type console.log(item); } }); // Console output: // 3 p elements 2. Element series attribute traversalElement Traversal adds five properties to DOM elements:
With these new attributes, it is much easier to traverse Still taking the above example: // Get the first element let currentElement = document.querySelector(".article").firstElementChild; // Traverse child elements while (currentElement) { console.log(currentElement); // Get the next element currentElement = currentElement.nextElementSibling; } This makes the process more concise. Currently IE9 and above, as well as all modern browsers, support these properties. This is the end of this article about using You may also be interested in:
|
<<: CSS+HTML to implement Skeleton Screen loading placeholder animation effect (with animation)
>>: How to prevent hyperlinks from jumping when using a link
The development of Docker technology provides a m...
Recently, I need to make a back-to-top button whe...
Origin of the problem When using docker, I unfort...
Table of contents 1. Initialize the map 2. Map Po...
This article mainly introduces common strategies ...
The previous three articles introduced common bac...
This article example shares the specific code of ...
Table of contents introduction Distinguish betwee...
Effect picture: 1. Introduction Your own applet n...
I solved a problem tonight that has been botherin...
This article example shares the specific code of ...
The Meta tag is an auxiliary tag in the head area...
Without further ado, I will post the code for you...
Table of contents mysql log files binlog Binlog l...