I'm trying to add dynamically information from an XML and add to an div. My idea is to add the new div inside the existing div (not mandatory.. i can also actually add to the existing div)
JS
var newDiv = document.createElement("div"); //new Div
newDiv.appendChild(sideTab);
var existingDiv = document.getElementById("vertical"); //Existing div
document.body.insertBefore(newDiv,existingDiv);
sideTab will have something like that:
<ul class ="tab" >
<li><a href="#" class="tab"> Something</a></li>
</ul>
Existing div
<div class="left" id="vertical">
But when i execute i get this error: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
I'm trying to add dynamically information from an XML and add to an div. My idea is to add the new div inside the existing div (not mandatory.. i can also actually add to the existing div)
JS
var newDiv = document.createElement("div"); //new Div
newDiv.appendChild(sideTab);
var existingDiv = document.getElementById("vertical"); //Existing div
document.body.insertBefore(newDiv,existingDiv);
sideTab will have something like that:
<ul class ="tab" >
<li><a href="#" class="tab"> Something</a></li>
</ul>
Existing div
<div class="left" id="vertical">
But when i execute i get this error: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
Share Improve this question asked Sep 28, 2016 at 16:11 JosephJoseph 1692 gold badges5 silver badges13 bronze badges 7-
3
Where have you defined
sideTab
? – brk Commented Sep 28, 2016 at 16:13 -
2
seems like whatever you have in
sideTab
variable is not of typeNode
, just what the error message says. – keymone Commented Sep 28, 2016 at 16:14 -
Speculation:
sideTab
's value is a string (of HTML) – Quentin Commented Sep 28, 2016 at 16:14 - 1 Then the error message very clearly explains what is wrong. – Kevin B Commented Sep 28, 2016 at 16:16
-
1
@Joseph — So it is a string and not a node. It needs to be a node. See
createElement
and friends. – Quentin Commented Sep 28, 2016 at 16:18
1 Answer
Reset to default 1Parse the string to DOM and add the element you want into the HTML.
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function() {
var newDiv = document.createElement("div"); //new Div
var parser = new DOMParser();
var el = parser.parseFromString(`<ul id="sideBar"><li><a>Something</a></li></ul>`, "text/html");
var element = el.getElementById("sideBar");
newDiv.appendChild(element);
var existingDiv = document.getElementById("vertical"); //Existing div
document.body.insertBefore(newDiv, existingDiv);
}
</script>
</head>
<body>
<div class="left" id="vertical"></div>
</body>
</html>
Fixed to work with string element.
Plunker has been fixed.