Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery .each works only on the first element

I'm having trouble understanding jqueries .each. I have the following code:

$('#testDiv').each(function(index, domEle){    
    $(this).text(index);
});

and the following HTML

<div id="p18">
    <div class="inner">
        <span>...</span>
        <p class="right">...</p>
        <div id="testDiv"></div>
    </div>
</div>
<div id="p19">
    <div class="inner">
        <span>...</span>
        <p class="right">...</p>
        <div id="testDiv"></div>
    </div>
</div>
<div id="p20">
    <div class="inner">
        <span>...</span>
        <p class="right">...</p>
        <div id="testDiv"></div>
    </div>
</div>

When the script runs it only works for the first testDiv, as it correctly sets the text to 0, however the other testDivs.

My overall goal is to write a script that will set the height of the div based on another div's height. The heights differ so I think a loop structure is the way to go (unless I am mistaken?)

What am I doing incorrectly with the jq code?

like image 285
Skye Avatar asked Jun 08 '12 12:06

Skye


1 Answers

You can't use the same #id for different elements. Try to rename the rest and you'll get the result you want

Or do this (works without adding any classes - cleaner code)

$('.inner div').each(function(index, domEle){    
    $(this).text(index);
});
like image 117
Zoltan Toth Avatar answered Sep 20 '22 09:09

Zoltan Toth