user6606700 user6606700 - 3 months ago 8
CSS Question

set background color for specific text in jquery

<!DOCTYPE html>
<html>

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#something:contains(yellow)").css("background-color", "yellow");
});
</script>
</head>


<body>
<div id="something">

Color it with yellow
<div>
Nothing to do with it
</div>
</div>
</body>
</html>


I want to set background-color as yellow only "Color it with yellow" text not "Nothing to do with it" but my code doing to whole div because id contain please suggest how to set color in my text "Color it with yellow"

Answer

Try this using nodeType===3 which gives you div text and wrap() to make it yellow

$(document).ready(function(){
    $('#something').contents().filter(function () {
         return this.nodeType === 3;
    }).wrap('<span class="yellow">');
});
.yellow{background-color:yellow}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div id="something">
  Color it with yellow
  <div>
    Nothing to do with it
  </div>
</div>

Comments