closest() in javascript

closest() method in javascript

closest() method is used to retrieve the parent or the closet ancestor of the given element which matches the selectors given in parameter.

If there is no ancestors or parent element, it returns null.

Example - Retrieving previous ancestor of the given element

Try Yourself

Example Explanation

  • In the above example we have three div element one inside another (idDiv1, idDiv2, idDiv3), button and a Javascript function is declared for it (fun_name();).
  • When the button is clicked Javascript function is called.
  • In the Javascript function, first we are getting the last child div element (document.getElementById("idDiv3");) and storing in elem1 variable.
  • In the next step using closest() method we are retrieving the current and the closet element upto the given ancestor (elem1.closest("#idDiv2");) and storing it in elem2 variable.
  • Finally using the alert method, we are displaying retrieved content (alert(elem2.outerHTML);).