document.getElementsByTagName
, document.getElementsByName
and document.getElementsByClassName
methods (not supported in all browsers). Superficially, they’re similar to arrays since they have length property and elements can be accessed by [index]. However, they’re not arrays; methods such as push(), slice() and sort() are not supported.
Consider the following HTML document:
<body>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
</body>
Let’s grab every paragraph node using getElementsByTagName and a jQuery selector:
var pCollection = document.getElementsByTagName("p");
var pQuery = $("p");
console.log("pCollection.length: ", pCollection.length);
console.log("pQuery.length: ", pQuery.length);
Both return the same nodes so the collection length is 3:
pCollection.length: 3
pQuery.length: 3
We’ll now add another paragraph element to the document and look at the collections again:
// add new paragraph
var newp = document.createElement("p");
newp.appendChild(document.createTextNode("Paragraph 4"));
document.body.appendChild(newp);
//
// display length
console.log("pCollection.length: ", pCollection.length);
console.log("pQuery.length: ", pQuery.length);
The result:
pCollection.length: 4
pQuery.length: 3
HTMLCollection objects are live. They are automatically updated whenever the underlying document changes. jQuery and most other JavaScript libraries use methods such as document.getElementsByTagName() but copy the resulting nodes to a real array. Therefore, it’s a query on the state of the document at that time: it is never updated.
There are advantages and disadvantages with both methods. For example, the following code causes an infinite loop since the HTMLCollection length increases as <p> elements are added:
var pCollection = document.getElementsByTagName("p");
for (var i = 0; i < pCollection.length; i++) {
document.body.appendChild(pCollection[i].cloneNode(true));
}
That said, there may be situations when a faster, native live HTMLCollection is more useful than a static collection of jQuery nodes or repeatedly making the same selection. Fortunately, we can pass any collection to jQuery when we want to manipulate it, e.g.
var pCollection = document.getElementsByTagName("p");
// ... add nodes, do work, etc ...
$(pCollection).addClass("myclass");
jQuery and other libraries can cut development effort but always check whether it’s possible to write more efficient code in plain old JavaScript without incurring additional file requests and processing overheads.
Frequently Asked Questions about JavaScript vs jQuery HTML Collections
What is the main difference between JavaScript and jQuery when dealing with HTML collections?
JavaScript and jQuery are both powerful tools for manipulating HTML collections, but they handle these tasks in different ways. JavaScript is a programming language that directly interacts with HTML collections, allowing for more control and flexibility. However, it can be more complex and requires a deeper understanding of the language. On the other hand, jQuery is a JavaScript library that simplifies many tasks, including handling HTML collections. It provides easy-to-use methods for manipulating HTML elements, but it may not offer the same level of control as pure JavaScript.
How can I convert an HTML collection to an array in JavaScript?
In JavaScript, you can convert an HTML collection to an array using the Array.from() method or the spread operator. Here’s an example using Array.from():let collection = document.getElementsByClassName('example');
let array = Array.from(collection);
And here’s an example using the spread operator:let collection = document.getElementsByClassName('example');
let array = [...collection];
How can I iterate over an HTML collection in jQuery?
In jQuery, you can use the .each() method to iterate over an HTML collection. Here’s an example:$('.example').each(function(index, element) {
console.log(index, element);
});
This will log the index and the element for each item in the collection.
Can I use jQuery methods on an HTML collection returned by a JavaScript method?
No, you cannot directly use jQuery methods on an HTML collection returned by a JavaScript method. This is because JavaScript methods return HTML collections, while jQuery methods return jQuery objects. However, you can convert the HTML collection to a jQuery object using the jQuery function $(), like so:let collection = document.getElementsByClassName('example');
let jQueryObject = $(collection);
Now you can use jQuery methods on jQueryObject.
How can I access individual elements in an HTML collection?
In both JavaScript and jQuery, you can access individual elements in an HTML collection using bracket notation, similar to how you would access elements in an array. For example, to access the first element in a collection, you would use collection[0].
Can I modify elements in an HTML collection?
Yes, you can modify elements in an HTML collection in both JavaScript and jQuery. In JavaScript, you can directly modify the properties of the elements, while in jQuery, you can use methods like .css(), .attr(), and .html() to modify the elements.
How can I filter elements in an HTML collection?
In jQuery, you can use the .filter() method to filter elements in an HTML collection. In JavaScript, you can convert the collection to an array and then use the .filter() method.
Can I use array methods on an HTML collection?
No, you cannot directly use array methods on an HTML collection because it is not an array. However, you can convert the collection to an array using Array.from() or the spread operator, and then use array methods on it.
How can I add elements to an HTML collection?
You cannot directly add elements to an HTML collection because it is a live collection that automatically updates when the document changes. However, you can add elements to the document, and they will automatically be included in the collection if they match the selector.
Can I use the .map() method on an HTML collection?
No, you cannot directly use the .map() method on an HTML collection because it is not an array. However, you can convert the collection to an array using Array.from() or the spread operator, and then use the .map() method on it.
Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.