2

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?

9
  • 3
    document.getElementById("t1").value="<span>inside tag</span>"; Commented Nov 20, 2015 at 6:36
  • yeah. Thats what i used. But that also isn't working. Commented Nov 20, 2015 at 6:39
  • 3
    A <textarea> doesn't normally allow for child elements. Only text content (its value). The one exception is if it's set to be contenteditable. Commented Nov 20, 2015 at 6:39
  • @HarshitaLal Then create a minimal example so we can see what you have, because using just .value should work. Commented Nov 20, 2015 at 6:40
  • @RohitAzad: Please don't put random words in backquotes. It makes it harder to read. Commented Nov 20, 2015 at 6:40

2 Answers 2

2

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";
Sign up to request clarification or add additional context in comments.

4 Comments

using .value prints "<span>inside tag</span>" as a string into the textarea rather than creating a span.
@HarshitaLal If you are trying to embed pure html within textarea the answer is no. It's not possible to create a span tag within textarea you can enter the HTML in string fromat only. The HTML <textarea> element represents a multi-line plain-text editing control.
Thanks for the answer. That was of great help.
@HarshitaLal You are welcome. You can mark this answer as the answer by clicking on it if it was of any help. Many Thanks
0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.