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.
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.
Share Improve this question asked Dec 5, 2017 at 20:31 youhanayouhana 3282 silver badges17 bronze badges 3- Possibly duplicate of stackoverflow./questions/2895318/appendchild-createelement – BASEER HAIDER JAFRI Commented Dec 5, 2017 at 20:33
- @BASEERHAIDER i don't think so. – entio Commented Dec 5, 2017 at 20:34
- @BASEERHAIDER : !! duplicate, your mentioned question asking about append child of a div tag, and my question is asking about add a direct child to document object, did you understood both of them? – youhana Commented Dec 5, 2017 at 20:40
2 Answers
Reset to default 4This 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.
I just had this error so wanted to clarify the reason ,
What you are doing using this mand 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)