Using the DOM parser I parsed a string , and then tried to append the object to a container, like so:
var newCategory =
"<div class=\"column-expenses-left\" id=\"newCategory"+ expenseCategoryCssName +"\">" +
"<hr />" +
"<div style=\"text-align: center;\">" +
"<?php echo $budgetExpense[\'ExpenseCategory\'][\'cssName\']; ?> " +
"<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 happening here? Is there a way to use the parser so that it creates a node of type DIV instead? Is this even a good idea?
You can't append document nodes (the result of parseFromString
). Instead take the child of the document object and append it:
var parser = new DOMParser();
var newNode = parser.parseFromString(newCategory, "text/xml");
stack.appendChild(newNode.documentElement);
Note, that your HTML is not XML-complient so you might get errors parsing it. In this case make sure you fix them (like duplicated alt
attribute,
entities).
However, in your case I doubt you need to parse XML at all. You can just append entire HTML string in the first place. For example like this:
var stack = document.getElementById('newCategories');
stack.insertAdjacentHTML('beforeend', newCategory);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments