Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through div's in jQuery

Tags:

jquery

I have the following script:

     $('#divs').children().each(
  function(){

   //Get Id's
   var id = $(this).attr('id').replace('id_','');
   alert(id);

  }
 );

With the markup of:

      <div id="divs">
     <div id="item_1">
         <div id="sub_1">
             ---
            </div>
            <input type="button" value="Submit"/>
        </div>

        <div id="item_2">
             <div id="sub_1">
                ---
             </div>
             <input type="button" value="Submit"/>
        </div>
  </div>

Basically, it loops out twice for each id="item_" set... I just want it to count the item_1, item_2, etc. divs. Not the sub_1, etc.

Any ideas how to fix this? Thank you!

like image 507
dzm Avatar asked Feb 25 '26 04:02

dzm


2 Answers

$("#divs > div").each(
    function(){
        //your function
    }
);
like image 130
VIT Avatar answered Feb 26 '26 18:02

VIT


You can sub select children: $('#divs').children('[id^=item]')

like image 32
Aaron Harun Avatar answered Feb 26 '26 18:02

Aaron Harun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!