0

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.

1 Answers1

3

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

Community
  • 1
  • 1
Terry
  • 14,099
  • 9
  • 56
  • 84
  • 1
    `$(this).parent().attr("id")` can be replaced with the something much, much faster and more compact `this.parentNode.id`. There really is no reason to use three jQuery function calls here. jQuery should be used only when it does the job better. – jfriend00 Apr 15 '12 at 15:52
  • If you want to get really technical there are lots of things wrong with his code, like `input`s nested in `label`s, etc. I just directly answered his question. – Terry Apr 15 '12 at 15:56
  • And, I suggested code that would make a better answer. You don't need to be defensive. You could incorporate the suggestion into your answer. I thought about posting a competing answer, but decided to try to get you to improve yours. Besides it's a pet peeve of mine when anyone (the OP in this case and then copied by you) uses jQuery in places where it's the inefficient way to do things. – jfriend00 Apr 15 '12 at 16:02
  • Sorry I didn't mean to sound defensive or hostile. I guess I'm just used to ignoring technicalities like that when I see OPs with < 10 rep. I always assume they are just asking to get a quick answer and will generally ignore proper ways of doing things anyways. Appending your suggestion along with a reference for similar cases for future readers. – Terry Apr 15 '12 at 16:10