PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 15, 2022

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

 October 15, 2022     appendchild, dom, html, javascript, parent-child     No comments   

Issue

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 ?


Solution

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>



Answered By - Aniket Panchal
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing