Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript array into a div

I just need a little tweak, I know all this code isn't perfect (far from it). Instead of writing the contents of the array into a div, I ideally want to create a new div for each number in the array and then add it to the card container?

balls90 = [ '1', '2', '3', '4', '5', '6','7','8','9','10','11', '12', '13', '14', '15', '16','17','18','19','20','21', '22', '23', '24', '25', '26','27','28','29','30','31', '32', '33', '34', '35', '36','37','38','39','40','41', '42', '43', '44', '45', '46','47','48','49','50','51', '52', '53', '54', '55', '56','57','58','59','60','61', '62', '63', '64', '65', '66','67','68','69','70','71', '72', '73', '74', '75', '76','77','78','79','80','81', '82', '83', '84', '85', '86','87','88','89','90' ];

function getNumbers(){

    var player1 = new Array();

    balls90.sort( function() { return Math.random() - .25 } );

    for ( var i=1; i<=12; i++ ) {   
        player1.push(balls90[i]);
        document.getElementById("cardContainer").innerHTML+=(balls90[i]);
    }

}
like image 312
paul Avatar asked Apr 04 '11 15:04

paul


4 Answers

Simple method, instead of appending to the div try appending to a variable, something like

var html='';
for (var i=1; i<=12; i++) {
    html+='<div>'+balls90[i]+'</div>';
}
document.getElementById('cardContainer').innerHTML+= html;
like image 158
Belinda Avatar answered Oct 01 '22 11:10

Belinda


You can easily use document.createElement("div") and appendChild()

var div = document.createElement("div");
div.innerHTML = (balls90[i]);
cardContainer.appendChild(div);

Example on jsfiddle.

Using this method will get you away from having to worry about yucky string concatenation.

like image 29
Mark Coleman Avatar answered Oct 01 '22 09:10

Mark Coleman


You can accomplish this with element.createChild() and element.appendChild().

like image 27
08Hawkeye Avatar answered Oct 01 '22 09:10

08Hawkeye


Try this

                var full_list = "";
                for(var i=0; i<balls90.length; ++i){
                    full_list = full_list + balls90[i]+ "<br>";
                } 

                $("#cardContainer").html(full_list);
like image 34
Ragnar921 Avatar answered Oct 01 '22 09:10

Ragnar921