Search code examples
jqueryparent

JQuery: When .each over children with parents with different ID's, the first Parent's ID persists


All, I've done my very best to figure this out, though possible examples I've found are far more complicated and it seems as though I'm the only one out there having this problem, so I'm coming to you for help, or perhaps just an explanation.

In the code below, I would expect to see three alerts in a row, tab-1, tab-2, and tab-3, but instead I see three alerts of tab-1. Why is this and what might be the solution to get the desired effect?

Thanks for your time and assistance.

The HTML

<div id="tab-1">
    <span class="test"></span>
</div>
<div id="tab-2">
    <span class="test"></span>
</div>
<div id="tab-3">
    <span class="test"></span>
</div>

The jQuery

$('.test').each(function() {
    alert($('.test').parent().attr("id"));
});


Solution

  • While your code is close, it's not quite right. You should be using:

    $('.test').each(function() {
        alert($(this).parent().attr("id"));
    });
    

    Updated JS Fiddle demo.

    The problem you're experiencing is that you're reselecting the array on each iteration of each(), and jQuery will simply return the attributes of the first element of the array that's returned.

    References: