[英]Vanilla JS: Add Class When A Different Class Is Under An Element
我要做的是在具有不同類或沒有類的元素下方時將類添加到具有特定類的特定元素。
例如,讓我們以這段代碼為例。
< p class="my-paragraph">This is a sentence.</p>
< p class="my-paragraph">This is a sentence.</p>
< p class="my-paragraph">This is a sentence.</p>
<button class="somebutton">Click Here</button>
< p class="my-paragraph">This is a sentence.</p>
< p class="my-paragraph">This is a sentence.</p>
< p class="my-paragraph">This is a sentence.</p>
<image src="URL" />
舉個例子,我想查看類名為“my-paragraph”的所有內容,當它下面沒有“my-paragraph”類的元素時,向它添加另一個類,在這個類中將是“nomargin”例子。
這就是最終輸出的樣子。
< p class="my-paragraph">This is a sentence.</p>
< p class="my-paragraph">This is a sentence.</p>
< p class="my-paragraph nomargin">This is a sentence.</p>
<button class="somebutton">Click Here</button>
< p class="my-paragraph">This is a sentence.</p>
< p class="my-paragraph">This is a sentence.</p>
< p class="my-paragraph nomargin">This is a sentence.</p>
<image src="URL" />
就我的一生而言,我無法弄清楚如何編寫代碼,而且這個問題已經讓我的大腦崩潰了幾天,而且冒名頂替綜合症是真實存在的。
我覺得我想從一個 for 循環開始,但我無法在它的邏輯方面到達那里。
如果可能的話,成為 Vanilla JS 會很棒。
將<p>
標記的分組放在包含 div 中,然后使用 css 設置容器樣式並利用 css :last-of-type()
選擇器將不同的樣式應用於最后一個 my-paragraph 可能更容易在按鈕或圖像之前標記。
<div class="paragraph-container">
<p class="my-paragraph">This is a sentence.</p>
<p class="my-paragraph">This is a sentence.</p>
<p class="my-paragraph nomargin">This is a sentence.</p>
</div>
<button class="somebutton">Click Here</button>
<div class="paragraph-container">
<p class="my-paragraph">This is a sentence.</p>
<p class="my-paragraph">This is a sentence.</p>
<p class="my-paragraph nomargin">This is a sentence.</p>
</div>
<image src="URL" />
然后像這樣的css
.paragraph-container .my-paragraph:last-of-type() {
margin: 0;
}
你甚至可能不需要容器,我總是不得不使用-of-type
css 選擇器來獲得我想要的東西
我認為 JDawwgy 的答案是最好的做法,但如果不能將段落標簽組包裝到 div 中(比如,也許你正在制作所見即所得),這里有一個直接的答案。
在 vanilla JS 中,您可以 (a) 獲取所有段落標簽,(b) 遍歷這些段落標簽,然后 (c) 檢測它們的下一個兄弟是否是另一個<p>
,然后 (d) 如果下一個兄弟是,則應用一個類不是<p>
。
const allParagraphs = document.querySelectorAll('p');
allParagraphs?.forEach((paragraphNode) => {
const nextSibling = paragraphNode.nextSibling;
if(nextSibling?.tagName.toLowerCase() !== 'p')
paragraphNode.className += ' nomargin';
});
你可以試試這個。
const children = [...document.getElementsByClassName("my-paragraph")];
children.forEach((child) => {
if (!child.nextElementSibling.classList.contains("my-paragraph")) {
child.classList.add('nomargin')
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.