Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of elements in document.getElementsByClassName() array

I'm calling

document.getElementsByClassName('fastSearch', 'document.forms'); 

in my js code on html.

Will I get the same order of elements everytime I call?

like image 353
Sergei Podlipaev Avatar asked Feb 20 '16 16:02

Sergei Podlipaev


1 Answers

Yes, you will, on conforming implementations, but what it returns is not an array, it's an HTMLCollection. The results will be in document order (top-down, depth-first traversal — which is a fancy way of saying, what it looks like when you look at the markup :-) ).

For example, with this document:

<div id="d1" class="a">
    <div id="d2" class="a">
        <div id="d3" class="a"></div>
    </div>
    <div id="d4" class="a"></div>
</div>
<div id="d5" class="a"></div>

getElementsByClassName("a") will reliably list them in order: d1, d2, d3, d4, d5.

Note that getElementsByClassName is not supported by some older browsers, notably IE8. Everything vaguely-modern that supports it also supports the more generally-useful querySelectorAll (which supports a query based on any CSS selector), which (perversely) is in IE8 as well.

Other notes:

  • On a conforming implementation, getElementsByClassName returns a live HTMLCollection, which means that if you add, remove, or change elements, the collection you already have will be updated. That can be useful and powerful, or surprising, depending on what you're doing with it.
  • querySelectorAll returns a snapshot NodeList, e.g., not a live HTMLCollection.

Example:

var byClassName = document.getElementsByClassName("a");
var bySelector = document.querySelectorAll(".a");
console.log("Before adding another one:");
console.log("byClassName.length = " + byClassName.length);
console.log("bySelector.length = " + bySelector.length);
var div = document.createElement("div");
div.className = "a"
document.body.appendChild(div);
console.log("AFTER adding another one:");
console.log("byClassName.length = " + byClassName.length);
console.log("bySelector.length = " + bySelector.length);
<div id="d1" class="a">
  <div id="d2" class="a">
    <div id="d3" class="a"></div>
  </div>
  <div id="d4" class="a"></div>
</div>
<div id="d5" class="a"></div>
like image 61
T.J. Crowder Avatar answered Nov 11 '22 01:11

T.J. Crowder