Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to climb to specific parent element by JavaScript?

Tags:

javascript

I have a small html code as blow :

<div class="main">
  <div class="comments">
    <div class="insider">
      <div class="text">
        some text
      </div>
    </div>
  </div>
</div>

I am currently at const ele = document.querySelector(".text") and I wish to dynamically go up from the aforementioned element until I reach a class which has the name of "comments" and not farther than that.

How can I achieve this by vanilla JavaScript using querySelector?

like image 289
Hypothesis Avatar asked Dec 05 '25 04:12

Hypothesis


1 Answers

You can't move from child element to parent element using document.querySelector(). However, there are multiple ways to select the parent of an element.

You can use Element.closest() method to get the closest ancestor element with the specified CSS selector.

document.querySelector(".text").closest('.comments');

.closest() method will traverse the .text element and its ancestor elements (heading towards the document root) until it finds a node that matches the provided CSS selector.

If the element on which .closest() method is called, matches the provided CSS selector, then that element is returned otherwise .closest() method returns the matching ancestor or null if not match is found.

like image 180
Yousaf Avatar answered Dec 06 '25 16:12

Yousaf