What's the jQuery equivalent for each():
$(".element").each(function(){
// do stuff
});
when attaching a function to a single element, like #element
?
What's the jQuery equivalent for each():
$(".element").each(function(){
// do stuff
});
when attaching a function to a single element, like #element
?
Use
first()
.each()
matches all elements, whilefirst()
matches only the first.There are other selectors too. When you use the id in the selector, you will only get one element. This is the main difference between
.element
and#element
. The first is a class that can be assigned to many elements, while the second is an id that belongs to only (at most) one element.You can still use each if only one (or 0) element is returned. Also, you can skip each altogether if you want to link an event. You use
each
when you want to execute a specific function for each element in the list of elements.If the intention is to call a (non-jQuery) function in a new scope I think using "each" still is a valid (and probably the most elegant) way and it stays true to the jQuery syntax although I agree to Alex, it feels wrong since it might have some overhead. If you can change the syntax use
$('#element')[0]
as replacement forthis
(as already mentioned in the accepted answer).Btw could someone with enough reputation please correct the comment of "zzzzBov" about the accepted answer?
$('#element')[0]
and$('#element').get(0)
ARE! the same, if you want the jQuery object use$('#element').first()
or$('#element').eq(0)
Behind the scenes,
each
is just afor
loop that iterates through each element in themap
returned byjQuery
.It is essentially† the same as:
† There's more to it than this, involving calling the function in the context of the map element etc.
It's implementation is to provide a convenient way to call a function on
each
element in the selection.You can always reference the jQuery object in a variable:
...then manipulate it.
If the reason you wanted
.each()
was to reference the DOM element asthis
, you don't really need thethis
keyword to do it, you can simply grab the DOM element out of the jQuery object.The two of these are equivalent, and will retrieve the DOM element that would be referenced as
this
in the.each()
.I'd note that it isn't necessarily bad to use each to iterate over a single element.
The benefits are that you have easy access to the DOM element, and you can do so in a new scope so you don't clutter the surrounding namespace with variables.
There are other ways to accomplish this as well. Take this example:
If there is only 1 element, you can access it normally using the selector.
Do you mean like $('#element').children().each() supposing you have something like a ul with an id and you want the li each inside it?