Well, there is one popular way to clean all classes except one like
jQuery('#d-one label').attr('class', 'main');
But, the above code also adds main
class even if there wasn't there at first.
One workaround is to check if it has the class main
or not and perform accordingly. But is there any way cleaner and shorter than this?
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="d-one">
<label for="" class="main one two three"></label>
</div>
<script>
jQuery('#d-one label').attr('class', 'main');
console.log(jQuery('#d-one label').attr('class'));
</script>
<div id="d-two">
<label for="" class="one two three"></label>
</div>
<script>
jQuery('#d-two label').attr('class', 'main');
console.log(jQuery('#d-two label').attr('class'));
</script>
<!-- This not just remove, but also add new class -->
<div id="d-three">
<label for="" class="one two three"></label>
</div>
<script>
if($( "#d-three label" ).hasClass( "main" )){
jQuery('#d-three label').attr('class', 'main');
}else{
jQuery('#d-three label').removeClass();
}
console.log(jQuery('#d-three label').attr('class'));
</script>