20

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\']; ?>&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 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?

2 Answers 2

43

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-compliant so you might get errors parsing it. In this case make sure you fix them (like duplicated alt attribute, &nbsp; 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);
0
3

You almost got it. The little error is that in parser you are indicating that is text/xml and provide HTML code.

So just tell to the parser that is HTML not XML.

var newNode = parser.parseFromString(newCategory, "text/html");
1
  • 2
    I know it's been years since you posted your answer, but your answer fixed my problem. Thanks
    – einacio
    Commented Dec 30, 2019 at 19:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.