Creating a 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 content to it? In the above case, I lost the previous content due to innerHTML. I want a new div every time to dynamically attach the image and the above val variable to it. The desired and current output demonstrated here

Thanks in advance.

+6
source share
4 answers

Check 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++; } }; 
+6
source

See document.createElement() and element.appendChild() .

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

Because you are likely to come across this in the near future: you can remove any element with this code:

 element.parentNode.removeChild(element); 
+5
source

Using createElement :

 function selecteditems() { var container = document.getElementById('showselecteditems'); for (var i=1;i<=53;i++) { var fld = document.getElementById('timedrpact'+i); if (fld) { var div = document.createElement("div"); div.appendChild(document.createTextNode(fld.value)); container.appendChild(div); } } } 

Full version using cloneNode (faster) and eventBubbling

Live demo

 var div = document.createElement("div"); var lnk = document.createElement("a"); var img = document.createElement("img") img.className="remove"; img.src = "https://uperform.sc.gov/ucontent/e14c3ba6e4e34d5e95953e6d16c30352_en-US/wi/xhtml/static/noteicon_7.png"; lnk.appendChild(img); div.appendChild(lnk); function getInputs() { var container = document.getElementById('showselecteditems'); for (var i=1;i<=5;i++) { var fld = document.getElementById('timedrpact'+i); if (fld) { var newDiv = div.cloneNode(true); newDiv.getElementsByTagName("a")[0].appendChild(document.createTextNode(fld.value)); container.appendChild(newDiv); } } } window.onload=function() { document.getElementById('showselecteditems').onclick = function(e) { e=e||event; var target = e.target||e.srcElement; // target is the element that has been clicked if (target && target.className=='remove') { parentDiv = target.parentNode.parentNode; parentDiv.parentNode.removeChild(parentDiv); return false; // stop event from bubbling elsewhere } } getInputs(); } 
+3
source

The syntax for dynamically creating a div is:

  DivId = document.createElement('div'); DivId.innerHtml ="text" 
+1
source

Source: https://habr.com/ru/post/956410/