Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • What is parents() method in jquery ?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 237
    Comment on it

    Hello Readers,

    parents() is the jquery method and it is same as parent() method but the difference is that parents() method return the all ancestors of the given selector which include parent, grandparent, great-grandparent, great-great-grandparent and so on. If we use parents() method without parameter then it returns all the ancestors and if we pass the filter parameter inside the parents() method then it gives the result as per filter parameter.

    Syntax :

    $(selector).parents(filter)
    

    filter : filter is the optional parameter which specifies a selector expression to search down the ancestors.

    Code Example :

    <html>
    <head>
    <style>
    .ancestors * { 
        display: block;
        border: 2px solid lightgrey;
        color: lightgrey;
        padding: 5px;
        margin: 15px;
    }
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $("span").parents().css({"color": "red", "border": "2px solid red"});
    });
    </script>
    </head>
    
    <body class="ancestors">body (great-great-grandparent)
      <div style="width:500px;">div (great-grandparent)
        <ul>ul (grandparent)  
          <li>li (direct parent)
            <span>span</span>
          </li>
        </ul>   
      </div>
    </body>
    
    </html>
    

    In the above code we use the parents() method and select all ancestors of the selector <span> tag and change it's color and border in jquery.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: