admin管理员组

文章数量:1327849

I've been looking over previously asked questions and can't seem to find a solution for my scenario...

I'd like to be able to loop through all children and children of children, etc...

the markup from design looks similar to this

<div>
  <div>
   <label></label>
  </div>
  <div>
   <label></label>
  </div>
  <div>
   <label></label>
  </div>
</div>

I'd like to be able to select all labels within a specific div, regardless of their direct parent.

I've been looking over previously asked questions and can't seem to find a solution for my scenario...

I'd like to be able to loop through all children and children of children, etc...

the markup from design looks similar to this

<div>
  <div>
   <label></label>
  </div>
  <div>
   <label></label>
  </div>
  <div>
   <label></label>
  </div>
</div>

I'd like to be able to select all labels within a specific div, regardless of their direct parent.

Share asked Jun 30, 2011 at 19:21 Weston WatsonWeston Watson 5,7446 gold badges25 silver badges25 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 5

I'd like to be able to select all labels within a specific div, regardless of their direct parent.

It's just CSS selector notation. Assuming that <div> has an ID of myDiv:

$('#myDiv label').each(function ()
{
    // do stuff
});

You do not need to keep stepping down through children in order to find labels within a specific div. This will do the job for you:

$('#idOfDiv label')

$('div label') will select any descendant of that div, regardless of depth. If you want it to be children or children of children, you can select like $('div > label, div > * > label')

Use the find function (instead of children) like so: $('#container').find('label')

$('div:first').find('label') will give you each label element

To select all labels:

$('label').something();

To select all labels contained in a div:

$('label', 'div').something();

本文标签: javascriptjQuery looping through children of childrenStack Overflow