SoFunction
Updated on 2025-03-01

js Element Traversal method in Traversal specification

Browsers that support the Element Traversal specification include IE 9+, Firefox 3.5+, Safari 4+, Chrome and Opera 10+.

For spaces between elements, the document node will not be returned before IE9, and all other browsers will return the document node.

In order to be compatible with the differences between browsers and not change the existing DOM standards, the Element Traversal specification is available.

This specification adds 5 attributes to the element

childElementCount
firstElementChild
lastElementChild
previousElementSibling
nextElementSibling

Detailed official documentation;http:///TR/ElementTraversal/

For spaces between elements, previous versions of IE9 will not return text nodes, while other browsers will return spaces 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,W3C Element Traversal SpecificationA new set of attributes is defined.

The Element Traversal API adds the following 5 attributes to the DOM element:

  • childElementCount: Returns the number of child elements (excluding text nodes and comments).
  • firstElementChild: Points to the first child element.
  • lastElementChild: Point to the last child element.
  • previousElementSibling: Points to the previous peer element.
  • nextElementSibling: Points to the next peer element.

Supported browsers have added these attributes to DOM elements. You don’t have to worry about blank text nodes using these elements, so you can easily find DOM elements.

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 this:

var i,len,child = ;
while(child != ){
 if( == 1){
  processChild(child);
 }
 child = ;
}

And using the new attributes added by Element Traversal, the code will become very concise:

var i,len,child = ;
while(child != ){
 processChild(child);
 child = ;
}

Browsers that support the Element Traversal specification are: IE9+, Firfox3.5+, Safari4+, Chrome and Opera10+.