admin管理员组

文章数量:1356733

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.

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.

Share Improve this question asked Nov 13, 2009 at 6:14 MichaelMichael 3273 silver badges9 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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.

Use the each method:

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

});

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");
});

本文标签: javascriptHow to loop though a jQuery result setStack Overflow