Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Parent div on button click [duplicate]

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
}
like image 352
Huma Ali Avatar asked Mar 15 '17 13:03

Huma Ali


People also ask

How to get a parent Element in javascript?

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.

How to access parent in jQuery?

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.

What is the parent Element in html?

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>.


1 Answers

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>
like image 184
Ionut Avatar answered Oct 19 '22 12:10

Ionut