6

How do you iterate through a group of selected jQuery objects so that you can perform jQuery functions on each object individually?

   
 <div class="foobar">abc</div>
 <div class="foobar">123</div>
 <div class="foobar">abc123</div>

I can select the group:

var foobarObjects = jQuery('.foobar')

But how would you go through each jQuery object in foobarObject and manipulate each one individually? I thought I could use jQuery().each but that only allows me to work with DOM objects, not jQuery objects. I also tried a for loop in conjunction with the jQuery().eq(i) function, but that seems to merge the items together.

2 Answers 2

25

Use $(this)

$('.foobar').each(function(){
  $(this).blah//refers to jquery object.
});
Sign up to request clarification or add additional context in comments.

4 Comments

B.T.W. if you need to set something like attribute or class on ALL items in group you can simply use $('.foobar').attr("blah", "blah");
Hey Stefan, how would you also retrieve the index of the element? Usually, I would use the callbacks, i and v, to get the index and value separately. Is there any way to do this with "this"?
@ArtemYevtushenko api.jquery.com/jquery.each the first argument is the index, second is the value
@StefanKendall yes, but I’m curious to know if there’s a way of using “this” and if there are any benefits. Practically having both callbacks isn’t an issue.
2

Within jQuery().each() you can use $(this) to use the jQuery functions on the current DOM object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.