Skip to content
Advertisement

Javascript/jQuery change word color by specific some text contains

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>
  1. I’m <– will be always black color
  2. 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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement