user1334653
user1334653

Reputation:

jQuery each() returns only first found value

I'm trying to get the IDs from my parent divs

<div id="btn1"><label class="btn"><input type="submit" value="Submit"/></label></div>
<div id="btn2"><label class="btn"><input type="button" value="Add"/></label></div>

jQuery function:

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

The function returns the value 'btn1' two times. It should return 'btn1', 'btn2'.

Thanks in advance.

Upvotes: 0

Views: 1973

Answers (1)

Terry
Terry

Reputation: 14219

You're using a selector for .btn again inside your loop. Change it to refer to the current element using this

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

Edit:

As per jfriend00

there really is no reason to use three jQuery function calls here. jQuery should be used only when it does the job better.

And a reference for some of these common scenarios: https://stackoverflow.com/a/4652402/803739

Upvotes: 3

Related Questions