If i have some mark-up that looks like:
<div class="box">
</div>
why does doing a jquery selector$('.box') return the element in an array?
i get an output in the console as:
[<div class="box"></div>]
and not:
<div class="box"></div>
If i have some mark-up that looks like:
<div class="box">
</div>
why does doing a jquery selector$('.box') return the element in an array?
i get an output in the console as:
[<div class="box"></div>]
and not:
<div class="box"></div>
A (valid) selector is not guaranteed to match a single element, but it is guaranteed to represent a set of matched elements that may
This set is best represented by a collection object containing zero or more elements.
If you had markup consisting of more than one .box element, what would you expect jQuery to return if not a collection consisting of both elements? document.querySelector() is different in that the method is designed to return the first matching element per spec, which is why document.querySelectorAll() exists (which is what jQuery uses internally before defaulting to its own implementation).
From Rick Strahl description
Selectors return a jQuery object known as the "wrapped set," which is an array-like structure that contains all the selected DOM elements. You can iterate over the wrapped set like an array or access individual elements via the indexer ($(sel)[0] for example). More importantly, you can also apply jQuery functions against all the selected elements.
Because it's not an array, it's an array-like jQuery object. You can use the object that $() returns just like you would when you chain your methods together like $().css().append().
The other reason it's array-like is because the selector you provide can actually grab many different elements, and most of the methods you can call on a jQuery object will affect all dom elements that your selector selected.
I hope this helps, and I do hope you do a bit more research into jQuery and how it works. It's an extremely useful library that it appears you don't yet fully comprehend.
Edit: As others have mentioned, if you do just want an element from a jQuery object and just use jQuery as a selector, you can use bracket accessors $(...)[0] or the get method $(...).get(0).