jQuery closest() method


Example

Returns the first element that matches the selector starting at the element and traversing up the DOM tree.

HTML

<div id="abc" class="row">
    <div id="xyz" class="row">
    </div>
    <p id="origin">
      Hello
    </p>
</div>

jQuery

var target = $('#origin').closest('.row');
console.log("Closest row:", target.attr('id') );

var target2 = $('#origin').closest('p');
console.log("Closest p:", target2.attr('id') );

OUTPUT

"Closest row: abc"
"Closest p: origin"

first() method : The first method returns the first element from the matched set of elements.

HTML

<div class='.firstExample'>
   <p>This is first paragraph in a div.</p>
   <p>This is second paragraph in a div.</p>
   <p>This is third paragraph in a div.</p>
   <p>This is fourth paragraph in a div.</p>
   <p>This is fifth paragraph in a div.</p>
</div>

JQuery

var firstParagraph = $("div p").first();
console.log("First paragraph:", firstParagraph.text());

Output:

First paragraph: This is first paragraph in a div.