Tengo algunos problemas para agregar un nuevo div a un padre existente que acabo de crear. Después de la creación del padre, compruebo su existencia. Pero cuando quiero agregarle el niño después de seleccionar el padre a través de su identificación, aparece un error. ¿Qué hago mal?
var uiDiv = document.createElement("div"); uiDiv.id = "f_jsonuiDiv"; uiDiv.innerHTML = "jsonUI controls"; console.log("uiDiv"); console.dir(uiDiv); //shows uiDiv object //select container div const parentId = "f_jsonuiDiv"; //which is the id of the newly created container div console.log("parentId: ",parentId); var parElement = document.getElementById(parentId); console.log("parElement: "); console.dir(parElement); //says: null ! //create directly //const newDiv = parElement.createElement("div"); //throws error as parElement does not exist ...... //create first, then append const newDiv = document.createElement("div"); newDiv.innerHTML = "NEW DIV"; //parElement.appendChild(newDiv); //throws error as parElement does not exist ...... uiDiv.appendChild(newDiv); //does not throw an error ```Parece que primero necesita agregar uiDiv al cuerpo (o cualquier otro padre), para obtenerlo con getElementById
document.body.appendChild(uiDiv); // This should be valid now const parElement = document.getElementById(parentId);Debe colocar el script después del cuerpo para que se cree el DOM.
O deforma tu código con
window.addEventListener('DOMContentLoaded', (event) => { //put your code here });
se ejecutará después de que se cargue la página
A recomendaría usar insertAdjacentElement e insertAdjacentHTML . Te hace la vida más fácil.
// insertAdjacentElement returns the newly created element const uiDiv = document.body.insertAdjacentElement(`beforeend`, Object.assign(document.createElement("div"), { id: "f_jsonuiDiv", innerHTML: "jsonUI controls" }) ); // so now you can inject it wit some html uiDiv.insertAdjacentHTML(`beforeend`,`<div>HI, I am the NEW DIV in town</div>`); #f_jsonuiDiv div { color: red; padding: 2px 1em; border: 1px solid #AAA; max-width: 400px; text-align: center; }