3

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.

youhana
  • 318
  • 2
  • 16

2 Answers2

4

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.

Dave Gillem
  • 476
  • 4
  • 10
1

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)

Thenad
  • 155
  • 2
  • 11