Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to create div inside a div by click on a button

What i want to do is create a div with text ADDED! inside the div ofclass="box1" , it work with id instead class, how to do that with class, Thank you

javascript

<script>
        function creatediv(){
            const creatediv = document.createElement('div');
            creatediv.innerHTML ="ADDED!";

            document.getElementsByClassName("box1").appendChild(creatediv);
        }
</script>

html

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div class="box1"></div>
<button class="creatediv" onclick="creatediv()">
   <i class="fa-solid fa-plus fa-xl"></i>
</button>

>Solution :

In case you are looking for an explanation as to why your specific code snippet is not working:
getElementsByClassName returns an array. You need to refer to it with index [0]

Refer working snippet below:

function creatediv() {
  const creatediv = document.createElement('div');
  creatediv.innerHTML = "ADDED!";

  document.getElementsByClassName("box1")[0].appendChild(creatediv);
}
<div class="box1"></div>
<button class="creatediv" onclick="creatediv()">
   Add<i class="fa-solid fa-plus fa-xl"></i>
</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading