0. What is the difference between an HTMLCollection
and a NodeList
?
Here are some definitions for you.
DOM Level 1 Spec - Miscellaneous Object Definitions:
Interface HTMLCollection
An HTMLCollection is a list of nodes. An individual node may be accessed by either ordinal index or the node's name or id attributes. Note: Collections in the HTML DOM are assumed to be live meaning that they are automatically updated when the underlying document is changed.
Interface NodeList
The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.
The items in the NodeList are accessible via an integral index, starting from 0.
So they can both contain live data which means that the DOM will update when their values do. They also contain a different set of functions.
You will note if you inspect the console if you run your scripts that the table
DOM element contains both a childNodes
NodeList[2]
and a children
HTMLCollection[1]
. Why are they different? Because HTMLCollection
can only contain element nodes, NodeList also contains a text node.
1. What is the difference between document.getElementsByTagName("td")
and $("td")
?
document.getElementsByTagName("td")
returns an array of DOM elements (a NodeList
), $("td")
is called a jQuery object which has the the elements from document.getElementsByTagName("td")
on its properties 0
, 1
, 2
, etc. The main difference is that the jQuery object is a little slower to retrieve but gives access to all the handy jQuery functions.
2. $("#myTable")
and $("td")
are objects (jQuery
objects). Why is console.log
also showing the array of DOM elements beside them, and are they not objects and not an array?
They are objects with their properties 0
, 1
, 2
, etc. set to the DOM elements. Here's a simple example: of how it works:
var a = {
1: "first",
2: "second"
}
alert(a[1]);
3. What is the elusive "NodeLists" all about, and how do I select one?
You have been retrieving them in your code, getElementsByClassName
and getElementsByTagName
both return NodeList
s