jquery .each works only on the first element

12,529

Solution 1

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

Solution 2

id selector returns maximum one element.

You should never have more than one element with the same id. it's an invalid HTML

This will work, but you should fix the HTML instead:

$('div[id="testDiv"]')...

What you should really do is:

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

Then select by the class:

$('.testDiv')...

Solution 3

That's not a problem with the each method. You have specified the same id for several elements, which is not supported.

Use a class instead, and you can find all the elements.

Demo: http://jsfiddle.net/Guffa/xaL4n/

Solution 4

You can not specify same div id in a html page.

<div id="testDiv"></div>

insteed of that, try

<div class="testDiv"></div>

and your function should look like

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

});

Solution 5

You have invalid html. Ids need to be unique. You should change id="testDiv" to class="testDiv"

HTML:

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

Javascript:

$('.testDiv').each(function(index, domEle){    
    $(this).text(index);
});
Share:
12,529
Skye
Author by

Skye

Updated on June 13, 2022

Comments

  • Skye
    Skye almost 2 years

    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?