I want color one word on a paragraph but I create this paragraph with TextNode then is display like some text.
Example :
<!DOCTYPE html>
<html>
<body>
<p>Click the button to create a Text Node.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var t = document.createTextNode("Hello World <span style=\"color: #BA0000\">error</span> ");
document.body.appendChild(t);
}
</script>
</body>
</html>
Use the textContent property to change the text of a span element, e.g. span. textContent = 'Replacement text' . The textContent property will set the text of the span to the provided string, replacing any of the existing content.
The HTML DOM createTextNode() method is used to create a Text Node with the specified text.
You want to create an element not text. The textNode is going to display whatever text you give it instead of build out the html you pass it. So you'll want to create the elements inidivually in variables or set the innerHTML of a parent element with whatever content you have like the <span>
.
Try creating an element like a paragraph tag then setting it's innerhtml like below:
var t = document.createElement('p');
t.innerHTML = "Hello World <span style=\"color:#BA0000\">error</span> ";
This will give you the element with the html in it like you want, isntead of just text. See the example below.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to create a Text Node.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var t = document.createElement('p');
t.innerHTML = "Hello World <span style=\"color:#BA0000\">error</span> ";
document.body.appendChild(t);
}
</script>
</body>
</html>
You need to create an element. Using createTextNode
just creates text.
Here's how you can achieve this using createElement
function myFunction() {
var span = document.createElement("span");
span.style.color = "#BA0000";
span.innerText = "error";
document.body.appendChild(span);
}
So your complete code will look something like this:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to make a BUTTON element.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var t = document.createTextNode("Hello World ");
var span = document.createElement("span");
span.style.color = "#BA0000";
span.innerText = "error";
document.body.appendChild(t);
document.body.appendChild(span);
}
</script>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With