Skip to content
Advertisement

How to create a div using JavaScript?

I have the following <div> which I have created using HTML and CSS. I don’t want these divs to be created when the page loads, instead I would like them to be created only when a JavaScript function is executed.

I would prefer if they were actually created by the function, if possible, rather than being hidden/unhidden

Is there a way I can add this exact HTML code inside the function, or will I need to use JavaScript to create these divs? If I need to use JavaScript would someone be able to explain how?

HTML

JavaScript

CSS

JavaScript

Thanks for all the answers but unfortunately I cannot seem to get this to work. When I create a new document with the code below all I get is a blank window and the following error. Error 1 (new page) Also when I try and add this code to my existing page I get a similar error, and nothing changes on the page. Error 2 (existing page) What am I missing?

JavaScript

Advertisement

Answer

The error is caused by a bad implementation of the appendChild() method. You are passing the argument as a string: document.appendChild("div") instead of the created element .appendChild(div). Also, you should specify to what tag you would like to append. In this case I’m using the <body> tag:

JavaScript

Try the following snippet:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement