1

I have grabbed the contents of a HTML file which i want to append to an element.

The contents of the HTML is shown like this:

console.log(data);

Output:

<style>
    .data{
        position:relative;
        width:100%;
        height:100%;
    }
</style>
<div id="data">
</div>

I then append it to a parent element like this:

function merge(data,id){
    var el = document.getElementById(id);

    console.clear();
    console.log(el);
    console.log(data);

    el.appendChild(data);       
}

The output for el does show the correct element that I am trying to append to.

But i seem to get this error:

Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

What does the error mean, and how do I correct the error?

Sir
  • 8,135
  • 17
  • 83
  • 146

2 Answers2

0

I think you are looking for innerHTML property, exactly as in this answer.

The reason it doesn't work is that appendChild is a method of DOM node, expecting a DOM node - you are supplying text data instead. See the method definition here.

Community
  • 1
  • 1
zencodism
  • 442
  • 4
  • 9
  • 1
    No. Inner HTML will replace my parent's current content and any event listeners tied to said contents.... thats not ideal. Explained here: http://stackoverflow.com/a/5113120/1076743 – Sir Dec 29 '15 at 00:06
  • Then [insertAdjacentHTML](https://developer.mozilla.org/pl/docs/Web/API/Element/insertAdjacentHTML) is your friend, as @WhiteHat suggested. – zencodism Dec 29 '15 at 00:10
0

First you create the objects:

var div = document.createElement("div");
div.innerHTML = data;

This will cause data to be turned into HTML objects that the DOM can use which are stored in the childNodes attribute of div.

var children = div.childNodes;
for(var i in children)
    el.appendChild(children[i]);

So, you can create some functions like:

function interpret_data(data) {
    var div = document.createElement("div");
    div.innerHTML = data;
    return div.childNodes;
}

function addChildrenTo(children, elem) {
    for(var i in children)
        elem.appendChild(children[i]);
}

function merge(data, id){
    addChildrenTo(interpret_data(data), document.getElementById(id));
}

That should do the trick!

NOTE: These functions aren't bullet proof so play with them to fit your needs:)

tkellehe
  • 659
  • 5
  • 11