tengo este codigo:
/* Creating whole HTML Units from HTML Element list */ function createHTMLUnit(unitstruct){ var tempElement; Object.entries(unitstruct).forEach(([key, value]) => { // First of all we start a loop if(typeof value==='object'&&key==='$child'){ //Find out that we have an Object and it's a child //If yes we append this as a child to the tempElement with call this function again tempElement.appendChild(createHTMLUnit(value)); }else{ //If not we reach a single element have to find out what we should do with it //Switch from the cases like '$tag', '$attr', '$child' or other (will be a value) switch(key){ case '$tag': //Createing the element in value tempElement = document.createElement(value); break; case '$attr': //Loop through the value and set attributes for the element Object.entries(value).forEach(([attrkey, attrvalue]) => { tempElement.setAttribute(attrkey, attrvalue); }) break; case '$child': //Element innerHTML return tempElement; break; default: //Return with the value to the previous loop return tempElement; break; } } }); var htmlUnitParam = { '$tag': 'div', '$attr': { 'class':'msg-box', 'id':'msg-box01' }, '$child': { '$tag': 'div', '$attr': { 'class':'msg-box-container', 'id':'msg-box-container01' }, '$child': '' } } document.body.appendChild(createHTMLUnit(htmlUnitParam));Si ejecuto esto, aparecerá un "Error de tipo no detectado: no se pudo ejecutar 'appendChild' en 'Nodo': el parámetro 1 no es del tipo 'Nodo'". error. Si desarmo cosas como:
var x = createHTMLUnit(value); tempElement.appendChild(x);'x' no estará definido después de que createHTMLUnit regrese (como verifiqué en Chrome Inspector, en el punto 'return tempElement;' tempElement mantiene su valor y la función devuelve indefinido ...) por lo que appendChild no puede aplicar nada al nodo.
¿Alguien tiene idea de cuál es el problema? ¿Y cómo puedo solucionarlo? (Y sí, debería usar recrusión y una función como esta...)
Está tratando de devolver un valor de la función, pero sus declaraciones de devolución están dentro de una función de devolución de llamada de bucle forEach. Regresar dentro del ciclo no regresa desde la función externa, por lo que al final del ciclo simplemente no devuelve nada.
Información relacionada sobre forEach return
Ese enlace contiene algunas otras alternativas, pero básicamente desea reemplazar el bucle forEach con un bucle for regular, pasando por Object.keys u Object.values y luego sus retornos deberían comenzar a funcionar como esperaba originalmente.
¡Gracias por todos!
Mientras tanto, solo encuentro otra forma (tal vez también sea un poco cómoda) para que funcione.
function createHTMLUnit(unitstruct, appendto){ var tempElement; Object.entries(unitstruct).forEach(([key, value]) => { if(typeof value==='object'&&key==='$child'){ createHTMLUnit(value, tempElement); }else{ switch(key){ case '$tag': tempElement = document.createElement(value); break; case '$attr': Object.entries(value).forEach(([attrkey, attrvalue]) => { tempElement.setAttribute(attrkey, attrvalue); }) break; case '$child': tempElement.innerHTML = value; return; break; default: createHTMLUnit(value, appendto); break; } } }); if(tempElement!=undefined){ appendto.appendChild(tempElement); } }Tal vez no sea tan agradable, pero funciona bien.