How to get the closest element by selector in js?
To get the closest element by a selector, you can use the element.closest()
. See the following example:
const closestElement = targetElement.closest(selector);
<ul id="parentElement" class="level-1">
<li id="ii" class="product-group">Web Development
<ul class="level-2">
<li class="child-1">HTML</li>
<li class="child-2">CSS
<ul class="level-3">
<li class="css-1">test-1</li>
<li class="css-2">test-2</li>
<li class="css-3">test-3</li>
</ul>
</li>
<li class="child-3">JAVASCRIPT</li>
</ul>
</li>
</ul>
Below js code selects the closest <ul>
element of the selected element and changes the background of the selected element to blue color :
<script>
const x = document.querySelector("li.child-1");
const closet = x.closest("ul");
closet.style.background = 'blue';
</script>