How To Use Closest() Method Using JavaScript?

Nov 22, 2021 . Admin



Hello Friends,

Now let's see example of how to use closest() method example. We will check how to use closest() method. This is a short guide on use closest() method in javascript. Here you will learn how to use javascript closest() method. Let's get started with how to use closest() method in javascript.

Here i will give you many example how to use closest() method using javascript.

Example : 1
<!DOCTYPE html> 
<html> 
    <head> 
        <title>How To Use Closest() Method Using JavaScript? - My Webtuts.com</title>
    </head> 
    <body>
        <h3>How To Use Closest() Method Using JavaScript? - My Webtuts.com</h3>
        <div id = "a1"> This is the first div element. 
            <h3 id = "t1"> This is a heading inside the div. </h3>
            <div id = "a2"> This is the div inside the div element. 
                <div id = "a3"> This is the div element inside the second div element. </div>
            </div>
        </div>
        <script> 
            var val1 = document.getElementById("a3");
            var b1 = val1.closest("#a1");  
            var b2 = val1.closest("div div");  
            var b3 = val1.closest("div > div");  
            var b4 = val1.closest(":not(#a3)");
            
            console.log(b1);
            console.log(b2);
            console.log(b3);
            console.log(b4);
        </script> 
    </body> 
</html>  
Output :

Example : 2

<html>
    <head>
        <title>How To Use Closest() Method Using JavaScript? - My Webtuts.com</title>
    </head>
    <body>
        <h3>How To Use Closest() Method Using JavaScript? - My Webtuts.com</h3>
        <div id = "tst"> This is the div element.
            <p id = "b1"> This is the paragraph element inside the div element.
                <h3 id = "h"> This is the child of the paragraph element.
                    <p id = "b2"> This is the child of heading element of the paragraph element. </p>
                </h3>
            </p>
        </div>
        <script>
            var val1 = document.getElementById("b2");
            var a1 = val1.closest("b1");
            var a2 = val1.closest("h3");
            var a3 = val1.closest("div");

            console.log(a1);
            console.log(a2);
            console.log(a3);
        </script>
    </body>
</html>  
Output :

It will help you...

#Javascript