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


<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>jQuery Hierarchy Selector Example</title>
    <script src="../lib/jquery-3.3.1.min.js"></script>
    <script type="text/javascript">

            // 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"});
<h1>This is a demo of use jQuery selectors.</h1>
    <div>This is a jQuery example html page.
            It demos how to use jQuery selectors.
        <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>
    <p>I will recommend it to others.</p>
    <p>I love it.</p>
    <p>All the selectors is easy to control.</p>
<p>jQuery selector save me a lot of time.</p>
<p>jQuery selector is the best.</p>
0 0 votes
Article Rating
Notify of

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

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x