Home > OS >  Change color of specific part of element string in JavaScript
Change color of specific part of element string in JavaScript

Time:07-24

I'm creating a chat application, and I want the users text's to be colored. Here is how I create the text element:

var item = document.createElement('li'); 
item.textContent = `[Anye]: hello`;
item.style.fontWeight = 'bold';
item.style.color = 'red';

This is how this code is executed:

Current

This, on the other hand, is what I would want:

Desired

Is there a way that I can change the color of only part of the text?

Note: The desired image was created using the console, and please keep in mind that the messages are not fixed, it's up to the user what they want to say.

I'm willing to use jQuery for this example, if needed.

Thanks!

CodePudding user response:

You can wrap the author in a span element and set style property.

var item = document.createElement('li'); 
item.style.fontWeight = 'bold';

const author = document.createElement("span");
author.innerText = "[Anye]: ";
author.style.color = 'red';

item.append(author);
item.innerHTML  = "hello";

document.body.append(item);

Or you can wrap the message in a span element and set a predefined style in CSS.

var item = document.createElement('li'); 
item.innerHTML = `[Anye]: <span>hello</span>`;
item.style.fontWeight = 'bold';
item.style.color = 'red';

document.body.append(item);
li span {
  color: initial;
}

  • Related