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

I read the documentation on toArray() here and tested it in the console. I can not find the difference between calling toArray() on the selector and calling the selector itself.

I got the same result in both directions, 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 elements matching the jQuery selector as an array.

However, it seems that just querying the element itself does the same. And it's a lot easier to write.

Does anyone know the difference between the two? If not, I do not understand the purpose of this function.

+5
source share
1 answer

Take this example from the docs :

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

If you do something like $('img').toArray().reverse() Reverse $('img').toArray().reverse() , you get an inverse array of DOM nodes.

This is because if you do not execute toArray() first, you will not have all the cool Array prototype methods available to you.

+9
source

All Articles