简体   繁体   中英

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]

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> 

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.

 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 !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM