2 回答

TA貢獻1828條經驗 獲得超13個贊
如果您想使用querySelectorAll,就像您在第一個答案的評論中所說的那樣(您的問題中不清楚),那么解決方案是依次使用兩個querySelectorAlls 。
document.querySelectorAll('div.element').forEach(
el => el.querySelectorAll('h1, h2, p').forEach(
el => el.style.color = 'red'
)
);
.footer {
background-color: blue
}
<div id="1">
<div class="element">
<h1>Test 1</h1>
<span>Link to interesting <a href="https://google.com">site A</a></span>
</div>
</div>
<div id="2">
<div class="element">
<h2>Test 2</p>
<span>Link to interesting <a href="https://google.com">site B</a></span>
</div>
</div>
<div id="3">
<div class="element">
<h3>Dont color me red!</h3>
<p>Test 3</p>
<span>Link to interesting <a href="https://google.com">site C</a></span>
</div>
</div>
<div class="footer">
<h2>This is my footer</h2>
<p>Do not color this text red!</p>
</div>
div.element>h1, div.element>h2, div.element>p
但到那時,在樣式表中使用可能會更直接。

TA貢獻1868條經驗 獲得超4個贊
在 vanilla CSS 中,您可以選擇元素內所需的項目<div>
,就像這樣
.element h1, .element h2, .element p {}
如果你想要更簡潔、更整潔的 CSS 代碼,你可以隨時查看 SASS。
在 SASS 中它看起來像這樣:
.element { h1, h2, p { color: red } }
您可以在這里找到 SASS: https: //sass-lang.com/
JS 中的選擇不會因為使用預處理器而改變。預處理器所做的就是允許您以某種方式編寫 CSS,然后將其轉換為普通 CSS 供瀏覽器讀取。
因此,如果你想通過JS以最干凈的方式選擇.element h1,.element h2,.element p,我會給這些特定元素一個類,例如“red”,然后在JS中使用這個類來選擇它們。
- 2 回答
- 0 關注
- 126 瀏覽
添加回答
舉報