adikitty CB adikitty CB - 2 months ago 10
HTML Question

Adding div tag below another div tag

I have a

div
tag with class
divstudent
, lets say this is
div1
tag. Now I want to create another div tag
div2
dynamically below this
div1
tag, not inside of the
div1
tag. I want to create outside of
div1
tag using javascript. How can I do that?

"div1"
<div class="divstudent"></div>

<!-- i want to be like this -->
<!-- "div1" -->
<div></div>

<!-- "div2" -->
<div></div>

<!-- "div3" -->
<div></div>

Answer

Try something like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Divs creator</title>

    <script type="text/javascript">
        window.onload = function () {
            var divReference = document.querySelector('.divstudent');
            var divCounter = 0;
            divReference.addEventListener('click', function () {
                var divToCreate = document.createElement('div');
                divToCreate.innerHTML = ++divCounter;
                divReference.parentNode.appendChild(divToCreate);
            }, false);
        }
    </script>
</head>
<body>
    <div class="divstudent">
        <input type="button" value="add div below divstudent">
    </div>

</body>
</html>