Ad

Can't Append Contents Of Page To Parent Element

- 1 answer

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?

Ad

Answer

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:)

Ad
source: stackoverflow.com
Ad