Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why i couldn't append a child node to the document object model directly?

Tags:

javascript

dom

While studying the Document object model today, I faced a problem of appending a newly created child on the document object directly, here is my code :

var newEl=document.createElement("textarea");
document.appendChild(newEl);

the resulted error is :

Uncaught DOMException: Failed to execute 'appendChild' on 'Node': Only one element on document allowed.

I know the solution is to either append it to document.body or document.documentElement , but I didn't find a reference pointing that the mentioned way is not correct for a specific reason.

accept my apologies for being a beginner.

like image 282
youhana Avatar asked Nov 25 '25 09:11

youhana


2 Answers

This may be what you're looking for if what you want to do is understand the spec and constraints surrounding the different items in the Node Tree. Basically, the Document can have only 1 type (HTML or XML) and 1 element/child (e.g <html>) and the element (<html> tag) can have multiple children (<body>, <head>, etc..), attributes, etc.. So the element (<html>) and its children can be appended to, but the document itself cannot.

Hope that helps.

like image 82
Dave Gillem Avatar answered Nov 27 '25 22:11

Dave Gillem


I just had this error so wanted to clarify the reason , What you are doing using this command document.appendChild(newEl);, is trying to add an element to the main document, but the main document has only one element allowed which is the main <html> tag.

So what you can do is either pick another element, or if you want to add it to the displayable area you should use document.body.appendChild(newEl)

like image 23
Thenad Avatar answered Nov 27 '25 23:11

Thenad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!