+ 1

Changing font color inside template literal JavaScript

Hello guys! me again. just trying to change the font color for a single update of string inside a template literal. ex: function damageTaken(){ let gdPoint = Math.floor((Math.random()*8) + 1); adventurerHP -= gdPoint; update(`You have received ${gdPoint} points of damage! \n`); document.getElementById("advHealth").innerText = `${adventurerHP} HP`; } So basically what i want to do is to add the "you have received ... points of damage" in red. But whenever i try to change it by adding a span to it, it changes all the other messages in the textbox. Thanks Schindlabua for your response, but i get a weird error on which the message loses its span property as soon as a different message appears in the textbox x.x

24th Apr 2019, 7:30 PM
Mariano Leonel Roura
3 Answers
+ 3
Side note! Using the style attribute is considered bad practice. I would add the following in your CSS: .red { color: red; } And then, in your javascript, you can do the following: let span = document.createElement('span'); span.setAttribute('class', 'red'); span.textContent = str; document.getElementById('health').appendChild(span);
24th Apr 2019, 7:38 PM
Schindlabua
Schindlabua - avatar
+ 2
Hard to say without seeing the code. I would guess that somewhere else in your code you are also doing `.innerHTML` or `.innerSomething` and that interferes with what we wrote above?
24th Apr 2019, 8:08 PM
Schindlabua
Schindlabua - avatar
+ 1
Thank you for your reply! I have edited the main question since i quoted the wrong code before x.x But i tried adapting it to your idea and it still doesnt work properly >.<
24th Apr 2019, 8:00 PM
Mariano Leonel Roura