Menu

JavaScript closest() method

JavaScript closest() method of the Element interface traverses the element until it finds a node that matches the specified CSS selector. 
Syntax of JavaScript closest method syntax is element.closest(css selector).

HTML code snippet


<article>
  <div id="article">
    This is article 
    <div id="title">
      Here is article title
      <div id="description">Here is article description</div>
    </div>
  </div>
</article>

JavaScript closest example

const desElement = document.getElementById("description");

// the closest ancestor with the id of "title"
console.log(desElement.closest("#title")); //this will return <div id="title">

// the closest ancestor which is a div in a div
console.log(desElement.closest("div div")); //this will return <div id="description">

// the closest ancestor which is a div and has a parent article
console.log(desElement.closest("article > div")); //this will return <div id="article">

// the closest ancestor which is not a div
console.log(desElement.closest(":not(div)")); //this will return <article>


Reference

-- https://developer.mozilla.org/en-US/docs/Web/API/Element/closest

No comments:

Post a Comment