Unable to add DOM element in DIV node: Uncaught HierarchyRequestError: failed to execute 'appendChild' in 'Node'

Using the DOM parser, I parsed the string and then tried to add an object to the container, for example:

var newCategory = "<div class=\"column-expenses-left\" id=\"newCategory"+ expenseCategoryCssName +"\">" + "<hr />" + "<div style=\"text-align: center;\">" + "<?php echo $budgetExpense[\'ExpenseCategory\'][\'cssName\']; ?>&nbsp;" + "<span>" + "<a href=\"#\" class=\"delete-category\"><img alt=\"\" src=\"/theme/all/img/Trash_can_small.png\" style=\"width: 15px; height: 15px; float: right;\" id=\"\" alt=\"Delete\"/></a>"+ "</span>" + "</div>" + "<hr />" + "<p class=\"pointer\" style=\"text-align: center;\"><img alt=\"\" src=\"/theme/all/img/add_to_yours.png\" style=\"display: inline-block;\" /></p>" + "</div> <!-- column-expenses-left -->"; // get the object to append to var stack = document.getElementById('newCategories'); var parser = new DOMParser(); var newNode = parser.parseFromString(newCategory, "text/xml"); stack.appendChild(newNode); 

However, I get the following error:

  Uncaught HierarchyRequestError: Failed to execute 'appendChild' on 'Node': Nodes of type '#document' may not be inserted inside nodes of type 'DIV'. 

I don’t quite understand what is going on here? Is there a way to use the parser to create a div type node instead? Is that even a good idea?

+5
source share
2 answers

You cannot add document nodes (result of parseFromString ). Instead, take the child of the document and add it:

 var parser = new DOMParser(); var newNode = parser.parseFromString(newCategory, "text/xml"); stack.appendChild(newNode.documentElement); 

Please note that your HTML is not XML-complient, so you may get errors parsing it. In this case, make sure that you correct them (for example, the duplicated attribute alt , &nbsp; ).

However, in your case, I doubt that you need to parse the XML at all. You can simply add the entire HTML line first. For example, for example:

 var stack = document.getElementById('newCategories'); stack.insertAdjacentHTML('beforeend', newCategory); 
+10
source

You almost got it. The small mistake is that in the parser you indicate that it is text/xml and provide HTML code.

So just tell the parser that HTML is not XML.

 var newNode = parser.parseFromString(newCategory, "text/html"); 
0
source

All Articles