Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

querySelector to select closest ancestor without jQuery

<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

like image 393
LIGHT Avatar asked Apr 29 '18 10:04

LIGHT


1 Answers

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()

like image 196
CertainPerformance Avatar answered Sep 19 '22 22:09

CertainPerformance