Skip to content Skip to sidebar Skip to footer

How Exactly Does Getelementsbyclassname Work In Chrome?, Specifically W.r.t. Nodelists & Doms

All of the following results were obtained using Google Chrome v36 & its console. While debugging a Wordpress plugin, I discovered that running this little Javascript snippet c

Solution 1:

As you can see, getElementsByClassName returns a HTMLCollection - that is, a live reference for your query.

What's happening is that you're expanding the live reference in the console after the DOM is ready, but logging it before the DOM is ready. Because it is a live reference, by expanding when the DOM is ready, when the HTMLCollection references the object in the memory, it sees that the DOM is ready and pulls from the finished DOM.

If, however, you expanded the reference while having paused the execution of the Javascript (this can be done with something like debugger), this is what you would get:

[item:function, namedItem:function]
    length:0__proto__:HTMLCollection0

because the DOM would not yet be ready then.

That's why the first logged reference showed up as [item: function, namedItem: function], because when you logged it, the DOM wasn't ready. Once the DOM was ready, it was logged as [a.someClass.someOtherClass, a.someClass.someOtherClass].

The length output, though, is just a number, not an object reference, and logs as is, which is why it prints 0 before the DOM is ready and 2 after it is - because that's exactly what's happening, since there are no DOM elements before the DOM is ready.

Solution 2:

Nodelist is a superset to HTMLcollection. Specifically Nodelist is the constructor which makes HTMLcollection.

var list = document.getElementsByClassName("classname"); console.log(list) Now you will see :

__proto__ : NodeList();
console.log(NodeList) //-> functionNodeList()

So a HTMLcollection is just a nodeList that contains elements and not text. (Nodelist's can contain text) to form a nodelist you must use the methods: Node.childNodes Element.classList

and probably some recursion to build it.

Post a Comment for "How Exactly Does Getelementsbyclassname Work In Chrome?, Specifically W.r.t. Nodelists & Doms"