Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating dynamic div using javascript

 <script>
    function selecteditems()
    {

    var i=1;
    var val="";
    while(i<=53)
    {

        if(document.getElementById('timedrpact'+i)!="")
        {
            val+=document.getElementById('timedrpact'+i).value;
            document.getElementById('showselecteditems').innerHTML=val;
            }
        i++;
        }

    }
    </script>

How to create a new div and add contents to it?In the above case i lost previous content due to innerHTML.I want new div each time for dynamically attach an image and the above variable val to it. The desired and current output demonstrated here

Thanks in advance.

like image 638
Anoop Avatar asked Oct 21 '13 12:10

Anoop


2 Answers

Check this Demo

<div id="output" class="out">

</div>

window.onload=function(){
    var output = document.getElementById('output');
    var i=1;
    var val="";
    while(i<=3)
    {

        if(!document.getElementById('timedrpact'+i))
        {
            var ele = document.createElement("div");
            ele.setAttribute("id","timedrpact"+i);
            ele.setAttribute("class","inner");
            ele.innerHTML="hi "+i;
            output.appendChild(ele);

        }
        i++;


    }
};
like image 88
Voonic Avatar answered Oct 06 '22 00:10

Voonic


Look at document.createElement() and element.appendChild().

var newdiv = document.createElement("div");
newdiv.innerHTML = val;
document.getElementById("showselecteditems").appendChild(newdiv);

Because you will likely encounter this in the near future: You can remove any element with this code:

element.parentNode.removeChild(element);
like image 23
Cobra_Fast Avatar answered Oct 05 '22 23:10

Cobra_Fast