I have the following html:
<div id = "CompOne">
<div id="btns">
<input type="button" value="Add" class="cartbtn" onclick="SetSubmitBundleValue(this)">
</div>
</div>
<div id = "CompTwo">
<div id="btns">
<input type="button" value="Add" class="cartbtn" onclick="SetSubmitBundleValue(this)">
</div>
</div>
And I want to get value of the parent div CompTwo
/ CompOne
on their button click. Is it possible to retrieve this value from the object passed through the 'this' keyword? Kindly help
function SetSubmitBundleValue(obj)
{
//Get Parent div
}
Use the closest() method to get the closest parent element by class, e.g. child. closest('. parent') . The closest() method traverses the Element and its parents until it finds a node that matches the provided selector.
The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.
A parent is an element that is directly above and connected to an element in the document tree. In the diagram below, the <div> is a parent to the <ul>. A child is an element that is directly below and connected to an element in the document tree. In the diagram above, the <ul> is a child to the <div>.
You can use parent()
method:
$('.cartbtn').on('click', function(){
var parent_id = $(this).parent().parent().attr('id');
console.log(parent_id);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "CompOne">
<div id="btns">
<input type="button" value="Add" class="cartbtn">
</div>
</div>
<div id = "CompTwo">
<div id="btns">
<input type="button" value="Add" class="cartbtn">
</div>
</div>
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