68 of 119 menu

The toArray method

The toArray method converts a set of jQuery elements into a JavaScript array. This is necessary so that JavaScript methods and functions can be applied to the array, such as sort the array or reverse.

Syntax

This is how we get the entire set of elements:

.toArray();

Example

Let's get all elements with p tag as an array using toArray method, reverse it using reverse and output the text content of the elements as a string using JavaScript join method:

<p>text1</p> <p>text2</p> <p>text3</p> <div>text4</div> function print(elems) { let arr = []; for (let i = 0; i < elems.length; i++) { arr.push(elems[i].innerHTML); } console.log(arr.join(' ')); } alert($('p').toArray().reverse());

See also

  • method get,
    which receives a set of elements
  • method filter,
    which filters the elements in a set
azbydeenesfrkakkptruuz