Reputation: 15
Looking to change the colour of specific characters. Having problems achieving this the return values are being overwritten with the new values. Tried placing this in a loop to parse through the characters but then got lost in the flow.
Here is the example:
$(document).ready(function() {
$("#container p").html(function(_, html) {
return html.replace(/([Aa])/g, '<span class="red">$1</span>');
});
$("#container p").html(function(_, html) {
return html.replace(/([Ee])/g, '<span class="blue">$1</span>');
});
$("#container p").html(function(_, html) {
return html.replace(/([Rr])/g, '<span class="green">$1</span>');
});
$("#container p").html(function(_, html) {
return html.replace(/([Oo])/g, '<span class="yellow">$1</span>');
});
});
.red {
color: red
}
.blue {
color: blue
}
.green {
color: green
}
.yellow {
color: yellow
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<p>aero aero aero</p>
</div>
jQuery returns scrambled HTML.
Upvotes: 0
Views: 132
Reputation: 392
To prevent overwriting values that have already been written, I created a new string to store the values then finally replace the old string.
$(document).ready(function() {
var newString = '';
for(var i = 0; i < $("#container p").html().length; i++) {
switch($("#container p").html()[i].toLowerCase()) {
case 'a':
newString += '<span class="red">' + $("#container p").html()[i] + '</span>';
break;
case 'e':
newString += '<span class="blue">' + $("#container p").html()[i] + '</span>';
break;
case 'r':
newString += '<span class="green">' + $("#container p").html()[i] + '</span>';
break;
case 'o':
newString += '<span class="yellow">' + $("#container p").html()[i] + '</span>';
break;
default:
newString += $("#container p").html()[i];
}
}
$("#container p").html(newString);
});
.red {
color: red;
}
.blue {
color: blue;
}
.green {
color: green;
}
.yellow {
color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<p>aero aero aero</p>
</div>
Upvotes: 1