Harshita Lal
Harshita Lal

Reputation: 33

Replacing text with <span> using javascript

I need to replace each word in the textarea by a span with unique id. I need the code in JavaScript. I have tried creating a DOM element and inserting it in text area using the following code.

var s = document.createElement('span');
var text=document.createTextNode("inside tag");
s.appendChild(text);                
document.getElementById("t1").appendChild(s);

t1 is the is the id of my text area. The above code isn't giving any result.

Also, I tried another method:

document.getElementById("t1").innerHTML="<span>inside tag</span>";

innerHTML isn't working here.

What do I do?

Upvotes: 2

Views: 2884

Answers (2)

Shahid Manzoor Bhat
Shahid Manzoor Bhat

Reputation: 1335

It has to be the value property instead of the innerHtml because of the fact that value property is used for setting the value for input/form elements. innerHTML on the other hand is normally used for div, span, td and similar elements.

So as you are using a textarea you shall go with value property.

document.getElementById("t1").value = "Whatever the text/html you want to insert here";

Upvotes: 2

Long Nguyen
Long Nguyen

Reputation: 11275

To change your value of text arena, you will have to do this:

document.getElementById('t1').value = '<span>inside tag</span>';

Upvotes: 0

Related Questions