JQuery addclass change
I have a question. How to insert a red background on only one, three and four?
$(function() {
$("#myid li").addClass("redcolor");
});
.redcolor {
background-color: red
}
.abcsize {
font-size: 36px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="myid">
<li>One</li>
<li class="abcsize">
Two
<ul>
<li>First</li>
<li>Second</li>
</ul>
</li>
<li>Three</li>
<li>Four</li>
</ul>
+3
source to share
3 answers
Use a not()
function to get all li except .abcsize and its children
$(function(){
$("#myid li").not('.abcsize,.abcsize li').addClass("redcolor");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style> .redcolor {background-color:red}
.abcsize {font-size:36px}
</style>
<ul id="myid">
<li>One</li>
<li class="abcsize">
Two
<ul>
<li>First</li>
<li>Second</li>
</ul>
</li>
<li>Three</li>
<li>Four</li>
</ul>
+4
source to share
Use a selector not
, make it
$("#myid > li:not(.abcsize)").addClass("redcolor");
Also >
only use to select children
Demo
$(function() {
$("#myid > li:not(.abcsize)").addClass("redcolor");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
.redcolor {
background-color: red
}
.abcsize {
font-size: 36px
}
</style>
<ul id="myid">
<li>One</li>
<li class="abcsize">
Two
<ul>
<li>First</li>
<li>Second</li>
</ul>
</li>
<li>Three</li>
<li>Four</li>
</ul>
+3
source to share