I have some trouble with appending a new div to an existing parent that I just created. After creation of the parent I check it's existence. But when I want to append the child to it after selecting the parent via it's id I get an error. What do I do wrong?
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 ```
CodePudding user response:
You need to put the script after the body let the DOM be created .
Or warp your code with
window.addEventListener('DOMContentLoaded', (event) => { //put your code here });
it will run after the page is loaded
CodePudding user response:
Seems like you need to add uiDiv
to body (or any other parent) first, in order to get it with getElementById
document.body.appendChild(uiDiv);
// This should be valid now
const parElement = document.getElementById(parentId);
CodePudding user response:
A would advise to use insertAdjacentElement
and insertAdjacentHTML
. It makes your life easier.
// 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;
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>