nearest() 方法

返回与从元素开始并遍历 DOM 树的选择器匹配的第一个元素。

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() 方法: 第一个方法返回匹配的元素集中的第一个元素。

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());

输出:

First paragraph: This is first paragraph in a div.