Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use <span> on paragraph with createTextNode

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>
like image 615
KasaiJo Avatar asked Feb 07 '20 15:02

KasaiJo


People also ask

How do you add text to span in 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.

Which of the method creates a text node with the specified text?

The HTML DOM createTextNode() method is used to create a Text Node with the specified text.


2 Answers

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>
like image 123
CoderLee Avatar answered Nov 14 '22 23:11

CoderLee


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>
like image 44
nopassport1 Avatar answered Nov 14 '22 21:11

nopassport1