jQuery Multiple Level Hierarchy Selector Example

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

jquery multiple level hierarchy selectors example

selector-hierarchy-example.html

<!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>
(Visited 106 times, 1 visits today)
READ :   jQuery Form Input Selector And Attribute Selector Example

Leave a Reply

Your email address will not be published. Required fields are marked *

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