13

I currently have the following html:

Apologies for edit, I was not paying attention when i wrote this.

 <div class ="left">
    <div>1</div>
    <div>2</div>
    <div>3</div>
</div>

I am using the JQuery .each command to iterate through each div using $('div').each. Although I only want to iterate through the divs inside the div with the class name 'left'.

I have tried using $('.left > div').each but it did not work.

Any help appreciated.

Daniel Li
  • 14,976
  • 6
  • 43
  • 60
James Mclaren
  • 666
  • 4
  • 10
  • 25

4 Answers4

20
$.each( $('.left'), function(i, left) {
   $('div', left).each(function() {

   });
})
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
9

Is this what you're lookng for?

$('div.left>div').each(function(){ /* do stuff */ });

Fiddle: http://jsfiddle.net/MLnBY/

Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
  • It works for this example, but it gets more complicated in my (simplified) code. my divs are inside a table if that matters? – James Mclaren Jul 18 '12 at 15:37
  • 1
    Ah, then remove the `>`. `$('div.left div').each(...);` This will iterate all divs that have an ancestor div with classname=left. – Paul Fleming Jul 18 '12 at 15:39
4
$(".left").children().each(function(i, elm) {
    alert($(this).html())
});
alexl
  • 6,841
  • 3
  • 24
  • 29
3

The syntax would be $(".left > div").each(function(){}); instead of .each(".left > div").

Update: Would want to use $(".left").children().each()

ayyp
  • 6,590
  • 4
  • 33
  • 47