I have a JavaScript function that uses document.innertext in order to change the text value of one of my <p>
elements. I want to make sure that some of the text has different colour, and from what I've gathered the best solution is to use <span>
tags inside the <p>
element. If I hardcode this into the html, it works fine.
However, if I use my innertext function to overwrite the content of my <p>
tag, the <span>
is instead printed out as if it was just a string. If I use the browser inspector then the <span>
is highlighted in black, meaning it is seen as a string. Both Chrome and Firefox do this and my page is a .php although if I rename it to .html it has the same effect. All the millions of code snippets online that do the exact same thing work for some reason, but mine doesn't.
The function is basically something like this document.getElementById("message").innerText = `<span style="color: red;">sample</span>: text`;
Instead of rendering "sample" in red and "text" in black, it renders "< span style="color: red;">sample text" all in black.
I hope I made myself clear. Thanks in advance for any help.
you need to use innerHTML property of document.
for ex:
document.getElementById("message").innerHTML = "<span style="color: red;">sample</span>: text";
I hope this would help you! Happy coding!