I have two divs with different ids but with the same classname. Example: Window1 & Window2…
<div id="Window1" class="name">
<span id="Admin"></span>
</div>
<div id="Window2" class="name">
<span id="Admin"></span>
</div>
I want to get the element id of “name” when I click on id “Admin”. Obviously the var solution is wrong below but want to set up something close to this…
var Window_id = $(".name").attr("id");
I hope this explains what I am trying to do. Thanks in advance.
First off, you can’t have two objects with the same ID. So you can’t have two objects with
id="Admin". You will have to give each one a different ID or use a common class name (or both). So you could change it to this:And, then use this jQuery to handle the click and get the id of the parent of the clicked object:
or, a little more efficiently using a little less jQuery:
My favorite option would actually be this because it’s a little more robust against some HTML changes (like if a new container div was introduced around the span):
.parent()or.parentNodeused in the first two options go up exactly one level in the DOM hieararchy..closest(".name")used in the third option goes up the parent hierarchy as far as needed until it finds a parent that matches the passed in selector. It’s a little more powerful and more likely to make sure you get the parent you want, even if the HTML changes a little bit. Not always required, but worth knowing about.