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
0. New operation: mkdir abc #Create a new folder ...
Sometimes it is slow to download large network fi...
Table of contents 1. Basic usage and logic 2. Fea...
Table of contents Tutorial Series 1. User Managem...
Table of contents Preface Benefits of axios encap...
Simple implementation of Mysql add, delete, modif...
The image can be easily pushed directly to the Do...
Trident core: IE, MaxThon, TT, The World, 360, So...
This article shares the specific code of JavaScri...
getElementById cannot get the object There is a s...
Preface: As far as I know, currently CSS can only...
This article shares the installation and configur...
String extraction without delimiters Question Req...
Table of contents Written in front Several storag...
First, let’s take a look at the general practices...