views:

72

answers:

3

I'm trying to learn jquery and I'm having some difficulty figuring out how to deal with a set of jquery results. Let's say I have some html like:

<div class="divClass">
  <p class="pClass1">1</p>
  <p class="pClass2">Some text.</p>
</div>
<div class="divClass">
  <p class="pClass1">2</p>
  <p class="pClass2">Some text.</p>
</div>
<div class="divClass">
  <p class="pClass1">3</p>
  <p class="pClass2">Some text.</p>
</div>

I want to loop through the div's with a class of "divClass", get the value contained in the child p with a class of "pClass1". Getting the set of div's with a class of "divClass" is easy with something like:

divs = $(".divClass");

But I'm not sure how to loop through "divs" and find the "pClass1" child, then get its value. Any help would be much appriciated.

+1  A: 

Use the each method:

$(".divClass").each(function() {

});
Andrew Hare
@cobbal - Nice call :)
Andrew Hare
and `this` refers to the element each iteration
cobbal
+2  A: 

You can use the each method, and then, look for the '.pClass' elements, in the context of this, which is the currently div being iterated:

var divs = $(".divClass");

divs.each(function () {
  alert($('p.pClass1', this).text());
});

Check the above example here.

CMS
This answers my question. Can you point me to where the second parameter of this statement is documented?$('p.pClass1', this)That is what I could not figure out how to do and could not find in the documentation. I still cannot find it after you've shown me how to do it.
Michael
+1  A: 

There are lots of ways.

For your specific scenario, I would try something like this:

$(".divClass .pClass1").each(function() {
    // Do whatever
});

If you wanted to do something with the div tags and the p tags, you could try the find method:

$(".divClass").each(function() {
   var p1Tags = $(this).find(".pClass1");
});
cbp