Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Parent() and Parents() method in jquery

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 559
    Comment on it

    Many times I stuck in an issue of getting parent elements or specific elements to build a specific functionality over it. So that I went through the jquery library, where I found 2 relevant methods to get the specific elements or parent elements. These are described below.

    1. Parent() Method

    The jQuery parent() method describe or returns the immediate parent element of each of these elements in a DOM Tree.

    This method reflect direct parent element of each elements in a DOM. This method call for a single level outcome.

    For Example=>

    HTML Code

    <div  class=”container”>
        <ul  class=”listings”>
            <li>List  01</li>
            <li  class=”list-item-02”>
                <span  class=”list-item-content”>List 02</span>
                </li>
        </ul>
    </div>
    

    jQuery Code

        var  parentClassName = $('.ist-item-content').parent().attr('class');
        alert(“Parent  Class Name ==> ” + parentClassName);
    

    Result:

        alert  box will show 
        Parent Class Name ==> "list-item-02"
    

     

    2. Parents() Method

    The jQuery parents() method reflect or returns all the parent elements hierarchy of each of these elements in a DOM Tree.

    This method reflect ancestral parent elements of each elements in a DOM. As per parent() method, this method is helps to get the single level outcome or multilevel outcome of parent hierarchy. It will easily understand by below example.

    For Example =>

    HTML Code

    <div  class=”container”>
        <ul  class=”listings”>
            <li>List  01</li>
            <li  class=”list-item-02”>
              <span  class=”list-item-content”>List 02</span>
            </li>
        </ul>
    </div>
    


    jQuery Code

        var  parentClassName = $('.ist-item-content').parents().attr('class');
        alert(“Parent  Class Name ==> ” + parentClassName);
    

    Result:

        alert  box will show 
        Parent Class Name ==> "Container listings  list-item-02"
    

    The above parents() method is very essential to get the first Parent element or specific parent elements. So overall we have a method to get the parent elements. We can get any specific parent elements of an element.

 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: