Convert to Array in jQuery
The toArray method converts a set of jQuery elements into a regular JavaScript array. This is necessary so that JavaScript methods and functions can be applied to this array, for example, sort this array or reverse.
Let's look at the following HTML code as an example:
<p>text1</p>
<p>text2</p>
<p>text3</p>
<div>text4</div>
Let's get all elements with p tag as an array using toArray method, reverse it using reverse. Then output the text content of the elements as a string using JavaScript method join.
To extract the text of elements and output the resulting array as a string, we will write a function print, whose parameter will be the inverted array:
function print(elems) {
let arr = [];
for (let i = 0; i < elems.length; i++) {
arr.push(elems[i].innerHTML);
}
alert(arr.join(' '));
}
print($('p').toArray().reverse());
Get all elements with the span tag as an array and capitalize the first letter of each element's text content. Output the resulting array of texts to the console as a string.