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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With