Why is my button element not created as a child in my parent div

Viewed 25

I have the following code. I want to add a button as a child of another element named element.

//parent div
const element = document.getElementById("idClass")

const button = document.createElement("button")

button.textContent = "Click me"

element.appendChild("button")

Can someone tell me why it doesn't work ?

1 Answers

You can put the Javascript code into the window.onload() function. Below is the working example for the same.

window.onload = () => {
    var element = document.getElementById("idClass");
    var button = document.createElement("button");
    button.textContent = "Click me";
    element.appendChild(button);
}
<div id="idClass"></div>

Related