Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between $("selector") and $("selector").toArray()

I was reading documentation on toArray() here and testing it out in the console. I cannot find the difference between calling toArray() on a selector and calling the selector itself.

I got the exact same result both ways, which is an array of DOM elements matching the selector. I even did another test

$("element").toArray()[0] === $("element")[0]

According to w3schools

The toArray() method returns the elements matched by the jQuery selector as an array.

However, it looks like just querying the element itself does the exact same thing. And it's a lot easier to write as well.

Does anyone know the difference between these two? If not, I don't understand the purpose of this function.

like image 987
Richard Hamilton Avatar asked Jun 11 '15 16:06

Richard Hamilton


1 Answers

Take this example from the docs:

If you do something like $('img').reverse(), you will get an error.

If you do something like $('img').toArray().reverse() you will get the reversed array of DOM nodes.

This is because if you don't perform the toArray() first, you won't have all the cool Array prototype methods available to you.

like image 73
Danny Delott Avatar answered Oct 19 '22 23:10

Danny Delott