<style type="text/css">
.card{
background:green;
}
</style>
<div class="card">
inside first
<div class="card" id="tryingtoselectthis">
inside second
<div class="card" id="myselector">
inside third
</div>
</div>
</div>
<script type="text/javascript">
console.log(document.querySelector("#myselector").closest(".card"));
</script>
I am trying to select #tryingtoselectthis
with the selector of .myselector
just using the class. Please note that there can be an unlimited number of child with the same class and all I want to do is select the just above parent with the same class.
parentNode
doesn't work. And, it is necessary to select the node using its class name.
No jQuery
You're almost there, but if you don't want the element you initially selected to be a possible result, you'll have to call closest
on its parent, not on the selected element.
console.log(document.querySelector("#myselector").parentElement.closest(".card").id);
.card {
background: green;
}
<div class="card">
inside first
<div class="card" id="tryingtoselectthis">
inside second
<div class="card" id="myselector">
inside third
</div>
</div>
</div>
Note that ancient browsers like IE will require a polyfill.
Element.closest()
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