Sunday, November 26, 2017

Part 10 - JQuery Traversing - #Parent Element Traversal | parent, parents and parentsUntil methods




Jquery Traversing?
In this tutorial will discuss about  jquery traversal specially, Parent Element Traversal.  Traversing means to reach to the particular element present in DOM Tree

Parent  Element Traversal
  1. parent(): It returns the direct parent element of the selected element.
  2. parents(): It returns all ancestor elements of the selected element.
  3. parentsUntil(): It returns all ancestor elements between two given arguments.

Child Element Traversal
  1. children(): It returns all direct children of the selected element.
  2. find(): It returns descendant elements of the selected element.

Sibling  Element Traversal 
  1. siblings() : It returns all sibling elements of the selected element 
  2. next() : It returns the next sibling element of the selected element.
  3. nextAll(): It returns all next sibling elements of the selected element
  4. nextUntil(): It returns all next sibling elements between two given arguments
  5. prev: It returns the previous sibling element of the selected element
  6. prevAll(): It returns all previous sibling elements of the selected element
  7. prevUntil(): It returns all previous sibling elements between two given arguments

# Example
Replace your html code with below code 

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="jquery-3.2.1.min.js"></script>
    <style>
        .ancestor * {
            display: block;
            padding: 10px;
            margin: 10px;
            border: 2px solid gray;
        }
    </style>

    <script>

    

        $(document).ready(function () {
            //*********Parent***********            
           // $("span").parent().css({ "border": "2px solid red" })
            //$("span").parent("li").css({ "border": "2px solid red" })

            //*********Parents***********  
            //$("span").parents().css({ "border": "2px solid red" })
            //$("span").parents(".div1").css({ "border": "2px solid red" })

            //*********ParentsUntil***********          
            $("span").parentsUntil(".ancestor").css({ "border": "2px solid red" })

        })
    </script>


</head>
<body>

    <div class="ancestor">
        Ancestor

        <div class="div1">
            Great grand Parent #div
            <ul>
                Grand Parent #ul
                <li>
                    Direct parent #li
                    <span>Child</span>
                </li>
            </ul>

        </div>


    </div>

   
</body>
</html>


No comments: