jQuery Tutorial Tutorials - jQuery .parents() method

jQuery .parents() method

The .parents() method in jQuery is used to get the ancestors of each element in the set of matched elements, optionally filtered by the selector, DOM node, or jQuery object passed.

jQuery .parents() method Syntax

.parents(selector)

jQuery .parents() method Example

example

Find all parent elements of the item with an id "python".

HTML

<ul>
    <li class="category">Language
        <ul>
            <li class="lang">Java
                <ul>
                    <li>Java tutorial</li>
                    <li>Java Examples</li>
                </ul>
            </li>
            <li class="lang">Python
                <ul id="python">
                    <li>Python tutorial</li>
                    <li id="pyex">Python Examples</li>
                </ul>
            </li>
        </ul>
    </li>
    <li class="category">Tools</li>
    <li class="category">Lautturi</li>
</ul>

jQuery

var parentElems = $( "#python" ).parents()
    .map(function(){
      return this.tagName;  
    })
    .get()
    .join(", ");

$('#log').html("The `#python` element's parents are:"+ parentElems);

Result

The `#python` element's parents are:LI, UL, LI, UL, BODY, HTML

Try now

example

Finds the parents element with a class lang for the element with an id pyex.

$( "#pyex" ).parents('.lang').css( "border", "1px solid red" );

Try now

Date:2019-08-26 14:05:49 From:www.Lautturi.com author:Lautturi