如何用CSS选择器排除特定类?仅提取仅含item-name类的文本
item-name类的元素文本(排除带active类的) Hey there! Let's figure out how to grab the text you need—you want elements that either only have the item-name class or at least don't have the active class alongside it. Here are two straightforward approaches depending on your exact needs:
1. 排除所有带active类的item-name元素(灵活方案)
If you just need to skip any element that has both item-name and active (even if it has other extra classes), use the :not() pseudo-class in your CSS selector. This works for most common scenarios where you only care about excluding the active state.
Code Example:
// Select all .item-name elements that don't have the .active class const targetElements = document.querySelectorAll('.item-name:not(.active)'); // Extract trimmed text from each matching element const itemTexts = Array.from(targetElements).map(el => el.textContent.trim()); // Use the texts however you need console.log(itemTexts);
2. 仅选择恰好只有item-name类的元素(严格匹配)
If you need to be super strict—only picking elements where the class attribute is exactly item-name (no other classes at all)—use an attribute selector instead. This targets elements with a perfect match for the class value.
Code Example:
// Select elements where class is exactly "item-name" const targetElements = document.querySelectorAll('[class="item-name"]'); // Extract the text content const itemTexts = Array.from(targetElements).map(el => el.textContent.trim()); console.log(itemTexts);
Quick Difference Breakdown:
- The first method (
:not(.active)) will include elements like<span class="item-name disabled">—it only filters out the ones withactive. - The second method (
[class="item-name"]) will only pick elements with no extra classes, so<span class="item-name disabled">would be excluded too.
Either way, both approaches will skip elements like <span class="item-name active"> which is exactly what you wanted!
内容的提问来源于stack exchange,提问作者Mirel

