This time I will bring you a detailed explanation of Element Traversal's implementation of element traversal. What are the precautions for Element Traversal's implementation of element traversal. The following is a practical case, let's take a look.
For spaces between elements, document nodes will not be returned before IE9. 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 elements
childElementCount firstElementChild lastElementChild previousElementSibling nextElementSibling
For spaces between elements, versions before IE9 will not return text nodes, while other browsers will Whitespace is returned as text nodes. This leads to inconsistent behavior when using the properties of childNodes and firstChild. 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 child elements (excluding text nodes and comments) number.
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 have added 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 sub-elements of an element across browsers, you needed to write code like this:
var i,len,child = element.firstChild; while(child != element.lastChild){ if(child.nodeType == 1){ processChild(child); } child = child.nextSibling; }
When using Element Traversal to add attributes, the code will change Very concisely:
var i,len,child = element.firstElementChild; while(child != element.lastElementChild){ processChild(child); child = child.nextElementSibling; }
The browsers that support the Element Traversal specification are: IE9, Firfox3.5, Safari4, Chrome and Opera10.
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 implement the diff algorithm in React
Vue implements two-way data binding function (with code)
The above is the detailed content of Element Traversal implements element traversal in detail. For more information, please follow other related articles on the PHP Chinese website!