I'm trying to discover a way of selecting all elements except one specific element. In this case, the :not(selector)
isn't working.
What's the best way to select all elements inside a container except for one of the specified elements?
.container not:(.test2) {
color: red
}
<div class='container'>
<p class='test'>test</p>
<p class='test'>test</p>
<p class='test'>test</p>
<p class='test'>test</p>
<p class='test2'>test 2</p>
</div>
It's quite easy to do this using the :not and :last-child pseudo-classes. The :not pseudo-class specifies elements that do not match a list of selectors and the :last-child selects the element if it is the last child among the other elements.
If you want to exclude root elements like html / body , you could select all elements within them. To exclude other elements, you could use the :not() pseudo-class to negate them. For instance, you could add an . excluded class to the elements.
Approach: Use the :not(selector), also known as negation pseudo-class which takes a simple selector as an argument and allows you to style all the elements except the element specified by the selector. We can never use nested negation :not(:not(selector)) because pseudo-elements are not simple selectors.
When designing and developing web applications, sometimes we need to select all the child elements of an element except the last element. To select all the children of an element except the last child, use :not and :last-child pseudo classes.
Correct the syntax (add ":" in front of "not"):
.container :not(.test2) {
color: red;
}
<div class='container'>
<p class='test'>test</p>
<p class='test'>test</p>
<p class='test'>test</p>
<p class='test'>test</p>
<p class='test2'>test 2</p>
</div>
This is the correct syntax, you should match the siblings instead of the parent..
.container *:not(.test2) {
color: red
}
<div class='container'>
<p class='test'>test</p>
<p class='test'>test</p>
<p class='test'>test</p>
<p class='test'>test</p>
<p class='test2'>test 2</p>
</div>
Use
.container :not(.test2) {
color: red;
}
To select everything except .test2
All pseudo classes begin with a :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With