Swapnil Rajja
Swapnil Rajja

Reputation: 107

Not able to append child in correct way

I have textarea and I want to append a paragraph tag, before I can get the value of textarea.

I am trying to do it with Javascript create element

var desc = document.createElement("p");
desc.innerHTML = description;
var abc = document.getElementById("textareaCode").appendChild(desc);
alert (abc);
 var comment = document.getElementById('textareaCode').value;
alert (comment);

This is the error message

[object HTMLParagraphElement]

Upvotes: 0

Views: 278

Answers (3)

Kaddath
Kaddath

Reputation: 6151

A textarea does not have the value property. You can get what's between the tags by using innerHTML:

var desc = document.createElement("p");
desc.innerHTML = 'blablabla';
var abc = document.getElementById("textareaCode").appendChild(desc);
var comment = document.getElementById('textareaCode').innerHTML;
alert (comment);
<textarea id="textareaCode"></textarea>

Note as Victor Popescu commented, that even if natively the HTML attribute value doesn't exist for a textarea, the setter exists in javascript so you can dynamically change the content with document.getElementById('textareaCode').value = 'test'; (but that won't add the attribute to the HTML, and more surprisingly won't update the DOM content, even if innerHTML will give you the right updated value).

About the rest of your problem, you can manipulate directly innerHTML to add text to existing one. But note that HTML tags will be rendered as text (< becomes &lt;, etc). Either you append an HTML object and it won't show in the textarea, either as text and it won't be treated as HTML:

var description = 'blablabla';
document.getElementById('textareaCode').innerHTML += '<p>' + description + '</p>';
var comment = document.getElementById('textareaCode').innerHTML;
alert (comment);
<textarea id="textareaCode">existing text</textarea>

Upvotes: 3

adel
adel

Reputation: 3507

var description ="hello world! love coding"; document.getElementById("textareaCode").value=description;
 var comment = document.getElementById('textareaCode').value;
alert (comment)
<textarea id="textareaCode"></textarea/>
u cant append a html element to a textarea instead u can do it with value !

Upvotes: 0

Milan Karman
Milan Karman

Reputation: 387

Are you sure this isn't working as expected? First you alert 'abc' which is an element. So the alert tells you that it's an element. After that you do alert(comment), which should be the alert you're looking for.

Upvotes: 0

Related Questions