I have html elements like follows with unknown hierarchy:
<div class="parent" name="parent">
<div>
<div>
<div>
<div onclick="get_parent(this)">
Nested Child 1
</div>
</div>
</div>
</div>
</div>
<div class="parent" name="parent">
<div>
<div onclick="get_parent(this)">
Nested Child 2
</div>
</div>
</div>
Is there any easy way to get parent of nested child by class or name?
Maybe there is some alternative to child.parentElement
or child.parentNode
I am not aware of which may help me?
Or looping through all parents until I get needed class
or name
is the only possible choice?
Use the closest() method to get the closest parent element by tag, e.g. child. parentElement. closest('div') . The closest() method traverses the Element and its parents until it finds a node that matches the provided selector.
parent: Using this, the parent element will be selected. child: Using this, the direct child element of the specified parent element will be selected.
I think closest
is the best solution.
function get_parent(elem) {
/*** For Class ***/
// var x = elem.closest(".parent").className;
/*** For Name ***/
var x = elem.closest(".parent").attributes["name"].value;
document.getElementById("demo").innerHTML = x;
}
<div class="parent" name="parent1">
<div>
<div>
<div>
<div onclick="get_parent(this)">
Nested Child 1
</div>
</div>
</div>
</div>
</div>
<div class="parent" name="parent2">
<div>
<div onclick="get_parent(this)">
Nested Child 2
</div>
</div>
</div>
<p id="demo"></p>
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