Distinguishing HTMLCollections, NodeLists, and Object Arrays in DOM
When accessing DOM nodes, developers often encounter HTMLCollections, NodeLists, and object arrays. Understanding the differences between these data structures is crucial to effectively manipulate the document structure.
HTMLCollections vs. NodeLists
HTMLCollections and NodeLists share similarities as node collections, but they have distinct characteristics:
- Content: HTMLCollections contain only Element nodes, while NodeLists can hold any type of node.
- Methods: In addition to methods common to all collections, HTMLCollections provide the namedItem method for accessing elements by name.
Live vs. Snapshot Collections
DOM collections can be either live or snapshot:
- Live: Collections update automatically when changes are made to the DOM.
- Snapshot: Collections remain fixed, regardless of DOM modifications.
DOM collections returned by browser methods (e.g., getElementsByTagName) are typically live, while jQuery selections are snapshots.
Arrays vs. Object Arrays
While jQuery objects appear as arrays in console logs, they are actually object arrays:
- Arrays: Sequential collections accessed using numeric indices.
- Object Arrays: Arrays where elements are accessed using both numeric and named properties.
Selecting Nodes
Using Document Methods:
- document.getElementsByTagName("td"): Returns an HTMLCollection of all td elements.
- document.getElementsByClassName("myRow"): Returns a NodeList of all elements with the "myRow" class.
Using jQuery:
- $("td"): Selects all td elements and returns a jQuery object, an object array.
Example Script
The provided script demonstrates the differences between data structures:
- console.log('[123,"abc",321,"cba"]=[123,"abc",321,"cba"]: Compares arrays.
- console.log('{123:123,abc:"abc",321:321,cba:"cba"}={123:123,abc:"abc",321:321,cba:"cba"}: Compares object arrays with object syntax.
- console.log('Node=',Node): Logs the global Node object, which is an object array representing node types.
- console.log('document.links=',document.links): Logs an HTMLCollection of links.
- console.log('document.getElementById("myTable")=',document.getElementById("myTable")): Logs a single element, not a collection.
- console.log('document.getElementsByClassName("myRow")=',document.getElementsByClassName("myRow")): Logs a NodeList of elements with the "myRow" class.
- console.log('document.getElementsByTagName("td")=',document.getElementsByTagName("td")): Logs an HTMLCollection of all td elements.
- console.log('$("#myTable")=',$("#myTable")): Logs a jQuery object representing the #myTable element.
- console.log('$("td")=',$("td")): Logs a jQuery object array containing all td elements.