I have a simple question with jQuery Css.
I would like to change color of my text by specific word contains using jQuery.
I have example like this:
<div class="me">I'm Groot</div>
- I’m <– will be always black color
- Groot <– will be always green color and Groot sometimes can be change with another word.
How can I do that with jQuery or javascript?
Advertisement
Answer
You could replace all occurrences of your specific text snippets with custom styled html elements:
const yourName = "Groot";
const element = document.querySelector(".me");
element.innerHTML = element.innerHTML
.replace("I'm", `<span class="black-class">I'm</span>`)
.replace(yourName, `<span class="green-class">${yourName}</span>`);
Alternatively you can also make everything green except the I'm like this:
.me {
color: green;
}
element.innerHTML = element.innerHTML
.replace("I'm", `<span class="black-class">I'm</span>`);
This way not only Groot is colored green but everything inside of the div. That way your JavaScript doesn’t need to know the name.