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
Several Differences Between MySQL 5.x and MySQL 8...
SVN service backup steps 1. Prepare the source se...
Table of contents Preface 🍹Preparation 🍲vue3 usag...
The browser is probably the most familiar tool fo...
Table of contents 1. Get the first link first 2. ...
<br /> English original: http://desktoppub.a...
0. Introduction August 18, 2016 Today, I noticed ...
Placing a search box in the top menu bar is a com...
.y { background: url(//img.jbzj.com/images/o_y.pn...
Some attributes about elements In the daily devel...
0. System requirements CPU I5-10400F or above Mem...
After the official release of Activiti7, it has f...
There are caches everywhere inside MySQL. When I ...
I will be learning MySQL next semester. I didn...
This article shares the specific code of JavaScri...