Home > Article > Web Front-end > How to traverse elements in js
This time I will show you how to perform element traversal in js, and what are the precautions for element traversal in js. The following is a practical case, let's take a look.
Browsers that support the Element Traversal specification include IE 9, Firefox 3.5, Safari 4, Chrome and Opera 10.
For spaces between elements, document nodes will not be returned before IE9, and all other browsers will return document nodes.
In order to be compatible with the differences between browsers without changing the existing DOM standard, the Element Traversal specification was created.
This specification adds 5 attributes to the element
childElementCount
firstElementChild
lastElementChild
previousElementSibling
nextElementSibling
Detailed official documentation; http: //www.w3.org/TR/ElementTraversal/
For spaces between elements, versions prior to IE9 will not return text nodes, while other browsers will return spaces as text nodes. This leads to inconsistent behavior when using the childNodes and firstChild properties. In order to make up for this difference while keeping the DOM specification unchanged, the W3C Element Traversal specification defines a new set of properties.
Element Traversal API adds the following 5 attributes to DOM elements:
childElementCount: Returns the number of child elements (excluding text nodes and comments).
firstElementChild: Points to the first child element.
lastElementChild: Points to the last child element.
previousElementSibling: Points to the previous sibling element.
nextElementSibling: Points to the next sibling element.
Supported browsers add these attributes to DOM elements. Using these elements, you don’t have to worry about blank text nodes, so you can find DOM elements very conveniently.
Here is an example. In the past, when you wanted to traverse all child elements of an element across browsers, you needed to write code like the following:
var i,len,child = element.firstChild; while(child != element.lastChild){ if(child.nodeType == 1){ processChild(child); } child = child.nextSibling; }
With the new attributes of Element Traversal, the code will become very concise:
var i,len,child = element.firstElementChild; while(child != element.lastElementChild){ processChild(child); child = child.nextElementSibling; }
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
How to operate Vue to make a proxy agent
How to deal with flickering when v-cloak is loaded in vue
The above is the detailed content of How to traverse elements in js. For more information, please follow other related articles on the PHP Chinese website!