jQuery Multiple Level Hierarchy Selector Example

This example will show you how to use jQuery ascent and descendant selectors to change Html div and p tag’s CSS style easily.

1. jQuery Selectors Example.

  1. The below picture shows the jQuery selectors’ example demo Html web page.
    jquery-multiple-level-hierarchy-selectors-example
  2. selector-hierarchy-example.html: This is the above Html web page source code with the jQuery selectors javascript code.
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>jQuery Hierarchy Selector Example</title>
        <script src="../lib/jquery-3.3.1.min.js"></script>
        <script type="text/javascript">
            $(function(){
    
                // Set all html tag p and div's padding and margin css value.
                $("p,div").css({padding:"10px", margin:"5px"});
    
                // Set all html div tag border css style.
                $("div").css({border:"green solid 5px"});
    
                // Set child div's css style inside parent div.
                $("div > div").css({background:"yellow", margin:"1em"});
    
                // Set all descendant div tag css style inside the most outer div.
                $("div div").css({border:"orange dotted 3px"});
    
                // Set third level and inner div css style.
                $("div div div").css({border:"blue dotted 3px", background:"orange"});
    
                // Set div first neighbor p html tag css style.
                $("div + p").css({border:"red dotted 3px", background:"white"})
    
                // Set the first div next two neighbor html p tag css style.
                $("div:eq(0) ~ p ~ p").css({border:"purple solid 2px"});
            });
        </script>
    </head>
    <body>
    <h1>This is a demo of use jQuery selectors.</h1>
    <div>dev2qa.com</div>
    <div>
        <div>This is a jQuery example html page.
            <div>
                It demos how to use jQuery selectors.
            </div>
            <p>Yes this is so cool.</p>
            <p>jQuery selector make get and change web page element easy.</p>
            <p>I love jQuery selectors.</p>
        </div>
        <p>I will recommend it to others.</p>
        <p>I love it.</p>
        <p>All the selectors is easy to control.</p>
    </div>
    <p>jQuery selector save me a lot of time.</p>
    <p>jQuery selector is the best.</p>
    </body>
    </html>

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Clicky