I'm trying to pass an anonymous function to the appendchild function.
I'm getting the following error message though:
Uncaught TypeError: Node.appendChild: Argument 1 does not implement interface Node.
Seems as if the anonymous function isn't returning the required type? In comparison, if I define a named function with the same code in it and pass that to the appendChild function I'm not getting an error.
See the following code for clarification:
// Option 1
function appendThis() {
var parent = document.getElementById("parent");
parent.appendChild(function () {
var child = document.createElement("div");
child.classList.add("child");
child.classList.add("red");
child.innerHTML = "appendThis()";
return child;
});
}
// Option 2
function appendThat() {
var parent = document.getElementById("parent");
var child = document.createElement("div");
child.classList.add("child");
child.classList.add("green");
child.innerHTML = "appendThat()";
parent.appendChild(child);
}
// Option 3
function createChild() {
var child = document.createElement("div");
child.classList.add("child");
child.classList.add("yellow");
child.innerHTML = "createChild()/appendThese()";
return child;
}
function appendThese() {
var parent = document.getElementById("parent");
parent.appendChild(createChild());
}
main{
height: 98vh;
width: 98vw;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
button{
height: 50px;
width: 200px;
}
hr{
width: 200px;
}
.parent {
height: 100%;
width: 100%;
}
.child{
height: 30px;
width: 200px;
text-align: center;
}
.red {
background-color: red;
}
.green {
background-color: green;
}
.yellow {
background-color: yellow;
}
<body>
<main>
<div id="parent"></div>
<hr>
<button class="red" onclick="appendThis();">AppendThis</button>
<button class="green" onclick="appendThat();">AppendThat</button>
<button class="yellow" onclick="appendThese();">AppendThese</button>
</main>
</body>
parent.appendChild(function () {
var child = document.createElement("div");
child.classList.add("child");
child.classList.add("red");
child.innerHTML = "appendThis()";
return child;
});
You did not actually execute your function there.
You need to add () after the function definition, if you want to execute it at this point.
This is what's called an IIFE - Immediately-Invoked Function Expression. More details on that can be found here: What is the (function() { } )() construct in JavaScript?