Reputation: 83
Given the following:
// all text should be red except in the excludeme id
$('body:not(#excludeme)').css('color', 'red');
// $('#excludeme').css('color','blue');
body {
color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
div text
</div>
<br />
<span>
<a id="excludeme">this text should be green</a>
<br />
span text
</span>
All text appears red, but the text in the excludeme id should remain green. Why does the :not selector not exclude the selected id?
Upvotes: 2
Views: 37
Reputation: 1247
As @TiiJ7 suggests, Check this if it suits, Click Me!!
Change CSS by this:
body {
color: red;
}
And JS by this:
$('#excludeme').css('color', 'green');
Upvotes: 0
Reputation: 2498
When you use :not()
then the color will be inherited from the parent
element.
Try below code -
// all text should be red except in the excludeme id
$("#excludeme").css('color', 'green')
$('body').css('color', 'red');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div>
div text
</div>
<br />
<span>
<a id="excludeme">this text should be green</a>
<br />
span text
</span>
</body>
Or you can also try this-
body{
color: red;
}
#excludeme{
color: green;
}
<body>
<div>
div text
</div>
<br />
<span>
<a id="excludeme">this text should be green</a>
<br />
span text
</span>
</body>
Upvotes: 1
Reputation: 10398
Your selector is selecting any body element that doesn't have an id of excludeme
. That just selects the body element of the document. You then apply the style to that element which overrides the style you applied in your CSS.
You end up with something like this where the #excludeme
element is not targeted in any way:
<html>
<head>
<style>
body {
color: green;
}
</style>
</head>
<body style="color: red">
...
<a id="excludeme">this text should be green</a>
...
</body>
</html>
You need to directly target that element to override the style.
Upvotes: 0
Reputation: 4413
The :not
is working as expected. If you inspect html code you can see that a
element does not have inline style that changes color to red. It is getting color from parent element because all other elements have red color. If you want you can declare a style for a element like this in css
#excludeme{
color: green;
}
You can read more about inheritance
in css
here
Upvotes: 1
Reputation: 2810
It is inherited from body, since body also has no excludeme
id, see:
// all text should be red except in the excludeme id
$('body:not(#excludeme)').css('color', 'red');
//$('#excludeme').css('color','blue');
body {
color: green;
}
#excludeme {
color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<body>
<div>
div text
</div>
<br>
<span>
<a id="excludeme">this text should be green</a>
<br>
span text
</span>
</body>
a
If you explicitly specify the color for excludeme
it will work.
Upvotes: 0