First I will explain the difference between NodeList
and HTMLCollection
.
Both interfaces are collections of DOM nodes. They differ in the methods they provide and in the type of nodes they can contain. While a NodeList
can contain any node type, an HTMLCollection
is supposed to only contain Element nodes.
An HTMLCollection
provides the same methods as a NodeList
and additionally a method called namedItem
.
Collections are always used when access has to be provided to multiple nodes, e.g. most selector methods (such as getElementsByTagName
) return multiple nodes or getting a reference to all children (element.childNodes
).
For more information, have a look at DOM4 specification – Collections.
What is the difference between
document.getElementsByTagName("td")
and$("td")
?
getElementsByTagName
is method of the DOM interface. It accepts a tag name as input and returns a HTMLCollection
(see DOM4 specification).
$("td")
is presumably jQuery. It accepts any valid CSS/jQuery selector and returns a jQuery object.
The biggest differences between standard DOM collections and jQuery selections is that DOM collections are typically live (not all methods return a live collection though), i.e. any changes to the DOM are reflected in the collections if they are affected. They are like a view on the DOM tree, whereas jQuery selections are snapshots of the DOM tree in the moment the function was called.
Why is console.log also showing the array of DOM elements beside them, and are they not objects and not an array?
jQuery objects are array-like objects, i.e. they have numeric properties and a length
property (keep in mind that arrays are just objects themselves). Browsers tend to display arrays and array-like objects in a special way, like [ ... , ... , ... ]
.
What is the elusive “NodeLists” all about, and how do I select one?
See the first part of my answer. You cannot select NodeList
s, they are the result of a selection.
As far as I know there is not even a way to create NodeList
s programatically (i.e. creating an empty one and adding nodes later on), they are only returned by some DOM methods/properties.