Buras
Buras

Reputation: 3099

How to create html elements dynamically?

I have an array

var elms = ["When?", "Why", "Where", ......]; 

I need to create the following elements

<html .. whatever> 

<div id="q1"> When?  </div>
<input type="text" id="a1"></input>

<div id="q2"> Why?  </div>
<input type="text" id="a2"></input>

<div id="q3"> Where?  </div>
<input type="text" id="a3"></input>

........
</html>

How can I do this ?

PS: My original page has only this array var elms and nothing else. I need to create all those divisions and inputs. I tried jquery, but messed up with the single and double quotes . . so I gave up.

Upvotes: 0

Views: 105

Answers (2)

Jay
Jay

Reputation: 2686

 var el;
 var idName;
 for(var i = 0; i < elms.length; i++){
   idName = "q" + i;
   el = document.getElementById(idName);
   el.innerHTML = elms[i];
 } 

Start your div ids with a index of 0 i.e id="q0" to make indexing easy

You can also do this with jquery:

 var el;
 var idName;
 for(var i = 0; i < elms.length; i++){
   idName = "#q" + i;
   $(idName).html(elms[i]); 
   // items in the html( .. ) can be done only in 
   // newer versions of jquery (I think) correct me if im wrong
 } 

If they don't already exists:

 var id;
 for(var i = 0; i < elms.length; i++){
  id = "q" + i;
  $("#containerDiv").append(
   "<div id="+id+">"+elms[i]+"</div><input type=\"text\" id=\"a2\"></input>"
   );
 }

Upvotes: 4

cssyphus
cssyphus

Reputation: 40038

Working jsFiddle Demo

HTML:

<div id="result"></div>
<input type="button" id="mybutt" value="Go" />

jQuery:

var nextbit, cnt=0;
var elms = ["When?", "Why", "Where", "How"];

$('#mybutt').click(function(){
    $(this).hide(); //Hide the button
    elms.forEach(function(item){
        cnt++;
        nextbit = '<div id="q"'+cnt+'>' +item+ '</div>';
        nextbit +='<input type="text" id="a"'+cnt+'></input>';
        $('#result').append(nextbit);
    });
});

Upvotes: 2

Related Questions