What Does the jQuery .toArray() Method Do?
The jQuery .toArray() method is a built-in function used
to convert a collection of matched DOM elements within a jQuery object
into a native JavaScript array. This article explains how
.toArray() works, why and when you should use it, and how
it simplifies working with native JavaScript array methods and raw DOM
elements.
How .toArray() Works
When you select elements using jQuery (for example,
$('div')), jQuery returns a jQuery collection object. This
object is "array-like"—it possesses a length property and
indexed elements—but it is not a true JavaScript array. Because of this,
it lacks native Array.prototype methods such as
.reverse(), .sort(), .reduce(),
or .some().
Calling .toArray() extracts all the underlying DOM
elements from the jQuery wrapper and returns them inside a standard
JavaScript array.
Syntax
$(selector).toArray();The method does not accept any parameters.
Basic Example
Consider the following HTML markup:
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
</ul>Using .toArray(), you can transform the selected
<li> elements into a native array:
// Select the elements and convert to an array
const itemsArray = $('li').toArray();
// Verify it is a true array
console.log(Array.isArray(itemsArray)); // true
// Access native array methods
itemsArray.reverse().forEach(element => {
console.log(element.textContent);
});
// Output: "Third", "Second", "First"In this example, the elements inside itemsArray are
native HTMLElement objects, not jQuery-wrapped objects.
Why Use .toArray()?
- Access to Native Array Methods: While jQuery
provides helper methods like
.each()and.map(), modern JavaScript features built-in methods like.filter(),.reduce(),.find(), and.sort()that operate only on true arrays. - ES6 Iteration and Spread Compatibility: Converting to an array ensures seamless integration with modern JavaScript APIs, functional programming patterns, and external libraries that expect standard arrays.
- Array Manipulation: Methods that modify array order
in-place, such as
.reverse()and.sort(), require a true array to function properly.
.toArray() vs.
.get()
The jQuery .get() method without arguments performs the
exact same operation as .toArray(). Both return an array of
all matched DOM elements. However, .toArray() is often
preferred in modern codebases because its name explicitly states its
purpose, making the code more readable and self-documenting.