This is my html :
<div id="my_box_one" class="head-div">
<div>
<div class="some_box">a</div>
<div class="some_box">b</div>
</div>
</div>
I want to get the ID of the parent div("#my_box_one") using the class of that div(".head-div")
$(document).ready(function(){
$(".some_box").click(function(){
var abc = $(this).parentsUntil(".head-div").attr("id");
// also tried $(this).parent(".head-div") -- same effect
alert(abc); // Shows as Undefined
});
});
I can do the following and it will work okay, but it doesn't seem right.
var abc = $(this).parent("div").parent("div").attr("id");
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.
getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.
Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to get or set the ID attribute value of an element. The following example will display the ID of the DIV element in an alert box on button click.
Show activity on this post. $('#loadMore'). on('click', function () { var page = $('#page'); var msg = $('#loadMoreMsg'); alert($(this). attr('id')); return false; });
You can use .closest( selector ), for example:
var abc = $(this).closest(".head-div").attr("id");
http://api.jquery.com/closest/
.parent( selector ) selects only immediate parent of the element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With