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