每位前端開發(fā)者都該掌握的 DOM 查詢技巧
我剛發(fā)現(xiàn)了一個非常實用的 DOM 查詢小技巧,它叫做 :scope,簡直是救星。準(zhǔn)備好讓你的選擇器精準(zhǔn)無比了嗎?
有時候,選對目標(biāo)元素感覺像是在猜謎。這種方法能讓你準(zhǔn)確鎖定所需元素,不用靠那些復(fù)雜的變通手段。
來看個 HTML 示例:
<ul>
<li><strong>A</strong></li>
<li><strong>B</strong></li>
<li><strong>C</strong></li>
<li><strong>D</strong></li>
</ul>
問題來了: 你只想選中 <ul> 下的奇數(shù)個 <li> 元素。我一開始試的是:
document.querySelectorAll(" > :nth-child(odd)")
不行。上述查詢會報錯,因為直接子代選擇器 > 缺少上下文錨點(diǎn),CSS 選擇器無效。于是我試了:
document.querySelectorAll("* > :nth-child(odd)")
這能執(zhí)行,但結(jié)果卻選中了所有的 <strong> 標(biāo)簽,完全偏離目標(biāo)。
解決方案是:利用 :scope 偽類選擇器。試試這個:
document.querySelectorAll(":scope > :nth-child(odd)")
下面是示例演示:
<!doctype html>
<html lang="en">
<body>
<ul onclick="highlightOdds(event)">
<li><strong>A</strong></li>
<li><strong>B</strong></li>
<li><strong>C</strong></li>
<li><strong>D</strong></li>
</ul>
<script>
function highlightOdds(event) {
let targets = event.currentTarget
.querySelectorAll(":scope > :nth-child(odd)");
for (let node of targets) {
node.style = "background-color: limegreen; color: white;";
}
}
</script>
</body>
</html>
點(diǎn)擊 <ul>,所有奇數(shù)位的 <li> 元素都會高亮成醒目的青檸綠。
只有奇數(shù) <li> 被選中,沒多余元素。
小技巧:自從 Edge 瀏覽器在2019年支持 :scope 以來,它在主流瀏覽器中表現(xiàn)穩(wěn)定。
下次項目試試看吧。
關(guān)注我,帶你解鎖更多 DOM 相關(guān)的神奇技巧。
接下來,我將按照您提供的詳細(xì)改寫要求,基于此中文翻譯進(jìn)行仿寫優(yōu)化。請稍候。
前端開發(fā)者必備的 DOM 查詢技巧揭秘
你是否曾在選擇頁面元素時感到無從下手?我最近發(fā)現(xiàn)了一個超級實用的小秘訣——:scope偽類,它能讓你的選擇器精準(zhǔn)無誤,簡直是救命稻草。準(zhǔn)備好讓你的 DOM 查詢變得鋒利如刀了嗎?
選擇正確的元素有時像猜謎游戲一般,而使用 :scope,你可以精確鎖定目標(biāo),無需那些繁瑣又易出錯的變通方案。
來看下面的 HTML 示例:
<ul>
<li><strong>A</strong></li>
<li><strong>B</strong></li>
<li><strong>C</strong></li>
<li><strong>D</strong></li>
</ul>
挑戰(zhàn)來了: 想選出 <ul> 標(biāo)簽下所有奇數(shù)序號的 <li> 元素。我最初嘗試的是:
document.querySelectorAll(" > :nth-child(odd)")
遺憾的是,這段代碼報錯了。原因在于,> 作為直接子代選擇器,缺少明確的參照元素,導(dǎo)致該 CSS 選擇器無效。接著我試了這個:
document.querySelectorAll("* > :nth-child(odd)")
雖然可以執(zhí)行,但結(jié)果卻匹配到了所有的 <strong> 標(biāo)簽,離預(yù)期目標(biāo)相去甚遠(yuǎn)。
這時,:scope 偽類派上用場了。試試這樣寫:
document.querySelectorAll(":scope > :nth-child(odd)")
下面的示例代碼演示了它的神奇效果:
<!doctype html>
<html lang="en">
<body>
<ul onclick="highlightOdds(event)">
<li><strong>A</strong></li>
<li><strong>B</strong></li>
<li><strong>C</strong></li>
<li><strong>D</strong></li>
</ul>
<script>
function highlightOdds(event) {
const targets = event.currentTarget.querySelectorAll(":scope > :nth-child(odd)");
for (const node of targets) {
node.style.backgroundColor = "limegreen";
node.style.color = "white";
}
}
</script>
</body>
</html>
只要點(diǎn)擊 <ul>,所有奇數(shù)位置的 <li> 元素就會亮起醒目的青檸綠背景。
每個奇數(shù)項都會被正確選中,絕無冗余。
專業(yè)提示:自從 2019 年 Edge 瀏覽器支持 :scope 后,這個偽類選擇器已經(jīng)在各大主流瀏覽器中表現(xiàn)得異常穩(wěn)定。
在你的下一個項目中,不妨嘗試一下這個技巧吧。