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.