Estoy tratando de pasar una función anónima a la función appendchild .
Sin embargo, recibo el siguiente mensaje de error:
TypeError no detectado: Node.appendChild: el argumento 1 no implementa la interfaz Node.
¿Parece que la función anónima no devuelve el tipo requerido? En comparación, si defino una función con nombre con el mismo código y la paso a la función appendChild , no obtengo un error.
Consulte el siguiente código para obtener una aclaración:
// 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; });En realidad, no ejecutó su función allí.
Debe agregar () después de la definición de la función, si desea ejecutarla en este punto.
Esto es lo que se llama IIFE - Expresión de función invocada inmediatamente. Se pueden encontrar más detalles al respecto aquí: ¿Qué es la construcción (función() { } )() en JavaScript?