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

   <div class = 'rowcontainer' id = "r<?php echo $studentid ?>" >
       <div class = 'name'><t><?php echo $firstname," ",$lastname; ?></t></div>
       <div class = 'ako'><t><?php echo $ako; ?></t></div>
       <div class = 'select'>
            <input type = 'checkbox' class = 'checkbox move'>
       </div>
   </div>

CSS

.rowcontainer {
    width: 100%;
    height: 30px;
}

.name {
    line-height: 30px;
    float: left;
    width: 60%;
    height: 100%;
    padding-left: 15px
}

.ako {
    line-height: 30px;
    text-align: center;
    float: left;
    width: 20%;
    height: 100%;
}

.select {
    line-height: 30px;
    text-align: center;
    float: right;
    width: 15%;
    height: 100%;
}

.checkbox {
    height: 17px;
    width: 17px;
    margin: auto;
    margin-top: 6px;
}

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?

<body>
    <script>
        let div = document.createElement("div");
        div.id = "div_id" ;
        div.className = "div_class";
        div.style = "background-color: red;";
        div.style.width = "100px";
        div.style.height = "100px";
        document.appendChild("div");
    </script>
</body>

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:

document.body.appendChild(div)

Try the following snippet:

let btn = document.getElementById('btnID');

btn.addEventListener('click', (e) => {
  
    let div = document.createElement("div");
    div.id = "div_id" ;
    div.className = "div_class";
    div.style = "background-color: red;";
    div.style.width = "100px";
    div.style.height = "100px";
    document.body.appendChild(div);  
  
});
<button id="btnID" style="margin:10px">Create Div</button>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement