I have the following string:
var songlist = '<div class="list-item" id="57902ccae53fa51716424034"><div class="media"><img src="{imgsrc}" alt="Mama Tried" /></div><h4 class="title">Mama Tried</h4><div class="song-controls"><button class="song play"><span class="fa fa-play"></button></div></div><div class="list-item" id="57902cddae7b54e264fcc6e4"><div class="media"><img src="{imgsrc}" alt="Blue Eyes Crying In the Rain" /></div><h4 class="title">Blue Eyes Crying In the Rain</h4><div class="song-controls"><button class="song play"><span class="fa fa-play"></button></div></div>';
Which I am converting to a NodeList through this custom function:
var toDom = function(str) {
var tmp = document.createElement("div");
tmp.innerHTML = str;
return tmp.childNodes;
};
console.log(toDom(songlist))
outputs NodeList [ <div#57902ccae53fa51716424034.list-item>, <div#57902cddae7b54e264fcc6e4.list-item> ]
, which you can browse through the devtools.
When I try to append the collection to a node...
document.getElementById("app-data").appendChild(toDom(songlist));
I get TypeError: Argument 1 of Node.appendChild does not implement interface Node.
Which is odd, because the docs for Node.appendChild()
say that argument 1 must be of type Node.
So, what type of element does Node.appendChild() expect? I've also tried HTMLCollection.
See JSFiddle.
To create a new element to be inserted at the end of a parent node, first use createElement to create it and then appendChild() for the newly-created element. The appendChild() method also works on existing child nodes, using which you can move them to new positions within the document.
To append using the innerHTML attribute, first select the element (div) where you want to append the code. Then, add the code enclosed as strings using the += operator on innerHTML.
A NodeList is a collection of document nodes (element nodes, attribute nodes, and text nodes). HTMLCollection items can be accessed by their name, id, or index number. NodeList items can only be accessed by their index number. An HTMLCollection is always a live collection.
Use appendChild to Append Data to Div in JavaScript Like the previous method, we first select the div by using one of the selectors. But instead of innerHTML , we use appendChild because of the problems discussed in the previous method. Before appending a child, we have to create the text node.
The problem is that Node.childNodes is a NodeList. So when you try to append it, it fails of course, because NodeList is not the same as Node. You could append child nodes one by one in loop:
var container = document.getElementById("app-data");
var childNodes = toDom(songlist);
for (var i = 0; i < childNodes.length; i++) {
container.appendChild(childNodes[i])
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With