JavaScript closest()The closest() method in JavaScript is used to retrieve the closest ancestor, or parent of the element matches the selectors. If there is no ancestor found, the method returns null. This method traverses the element and its parents in the document tree, and the traversing continues until the first node is found that matches the provided selector string. SyntaxIn the above syntax, selectors is a string containing a selector (like p:hover, etc.) used to find a node. Let's understand this method by using some illustrations. Example1In this example, there are three div elements and a heading on which we are applying the closest() method. Here, the selectors that we are using are the id selector, descendant selector, child selector, and :not selector. Test it NowOutput After the execution of the above code, the output will be - Example2This is another example of using JavaScript's closest() method. Test it NowOutput After the execution of the above code, the output will be - Next TopicJavaScript continue statement |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India