Becky
Becky

Reputation: 5585

Creating text node

I have a paragraph

<p>Student of Royal Institute!</p>

How can I add text within the paragraph using js?

<p>Student <script>var textnode = document.createTextNode("Walter"); this.appendChild(textnode);</script> of Royal Institute!</p>

So the final output is

<p>Student Walter of Royal Institute!</p>

Upvotes: 2

Views: 41

Answers (2)

Trevor Clarke
Trevor Clarke

Reputation: 1478

You can insert new text into a div. This should work for you:

<div id="text">Student of Royal Institute!</div>
<script>
document.getElementById("text").innerHTML = "New text to put into div.";
</script>

If you would like you can hook it up to a link like so: jsfiddle

Upvotes: 0

Roko C. Buljan
Roko C. Buljan

Reputation: 206151

A faar better idea would be to use a <span> holder to put text-values into

document.getElementById("name").innerHTML = "Walter";       // use for HTML
// document.getElementById("name").textContent = "Walter";  // OK for text
<p>Student <span id="name"></span> of Royal Institute!</p>


If you really want to create a textNode:

var textnode = document.createTextNode("Walter"); 
document.getElementById("name").appendChild(textnode);
<p>Student <span id="name"></span> of Royal Institute!</p>

Upvotes: 4

Related Questions