jQuery Tutorial Tutorials - jQuery .closest() method

jQuery .closest() method

The .closest(selector) method in jQuery is used to find the first element from the matched elements set and their ancestors,which matches the selector.

jQuery .closest() method Syntax

.closest(selector)
.closest(selector[,context])
.closest(selection)
.closest(element)
.closest(selectors[,context])

jQuery .closest() method Example

Begins with the current element,searches through their ancestors step by step,return the first matching elements.

example

Finds closest matching element and highlight them.

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

$("#pyex").closest('li').css('background','cyan'); 
// [<li id="pyex">]

$("#pyex").closest('.lang').css('background','cyan');
// [<li  class="lang">]

var python = document.getElementById( "python" );
$("#pyex").closest(python).css('background','cyan');
// [<ul  id="python">]

var category = $( ".category" );
$("#pyex").closest(category).css('background','cyan');
// [<li class="category">Language]

$("#pyex").closest(['.lang','body']).css('background','cyan');
// [<li  class="lang">,<body>]

Try now

Date:2019-08-26 13:21:30 From:www.Lautturi.com author:Lautturi