Convert Array of DOM Nodes to jQuery Collection
Converting a native JavaScript array of Document Object Model (DOM) nodes into a jQuery collection allows you to leverage jQuery's built-in methods, event handlers, and chaining capabilities on standard elements. This guide explains how to pass an array directly into the jQuery wrapper, handle similar structures like NodeLists, and apply jQuery methods to the resulting collection.
The Standard Method: The jQuery Wrapper
The most straightforward way to create a jQuery collection from an
array of DOM nodes is by passing the array directly into the root jQuery
function ($ or jQuery). jQuery is built to
accept an array of elements and wrap them into a new jQuery object.
// A standard array of DOM nodes
const nodeArray = [
document.getElementById('item1'),
document.getElementById('item2'),
document.getElementById('item3')
];
// Wrap the array in jQuery
const $collection = $(nodeArray);
// You can now use jQuery methods on the collection
$collection.addClass('highlighted');Handling NodeLists and HTMLCollections
Modern DOM querying methods like
document.querySelectorAll() return a NodeList,
while properties like element.children return an
HTMLCollection.
jQuery natively accepts NodeList and
HTMLCollection objects directly into the $()
wrapper without requiring manual conversion into a true JavaScript
array:
// Querying returns a NodeList
const nodeList = document.querySelectorAll('.card');
// Passing the NodeList directly to jQuery
const $cards = $(nodeList);
$cards.hide();If you need to ensure the structure is a standard array before
wrapping—for instance, to use native array methods like
.filter() or .map() first—you can convert it
using Array.from() or the spread operator
([...]):
const rawNodes = document.querySelectorAll('.card');
const filteredArray = Array.from(rawNodes).filter(node => node.dataset.active === 'true');
// Wrap the filtered array into a jQuery collection
const $activeCards = $(filteredArray);Using jQuery's .add()
Method
If you already have an existing jQuery collection and wish to merge
an array of DOM elements into it, use the .add() method.
This method accepts an array of elements and returns a new jQuery
collection containing both the original elements and the newly added
ones:
let $existingCollection = $('.primary-items');
const extraElements = [
document.createElement('div'),
document.getElementById('special-item')
];
// Merge array into a new jQuery collection
const $combinedCollection = $existingCollection.add(extraElements);Verifying the Collection
To confirm that the elements were correctly wrapped, you can inspect
the .length property of the resulting jQuery collection or
iterate through it using .each():
const elements = [document.body, document.documentElement];
const $wrapped = $(elements);
console.log($wrapped.length); // Outputs: 2
$wrapped.each(function(index, element) {
console.log(index, element.tagName);
});