Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a javaScript array to a HTML page?

Im trying to add an array to a webpage. I have tried a few different pieces of code show below but none of them work. I would like the output to be similar to a list like:

text1

text2

text3 ...

The code I have used so far is:

var i;
var test = new Array();
test[0] = "text1";
test[1] = "text2";
test[2] = "text3";

// first attempt
$('#here').html(test.join(' '));

// second attempt
$(document).ready(function() {
    var testList="";
    for (i=0;i<test.length; i++) {
        testList+=  test[i]  + '<br />';
    }
    $('#here').html('testList');
    songList="";
}); 

I am quite new to javaScript so I am not sure if I have just made a small mistake or if Im doing this in the wrong way. Also, above is a copy of all the code in my javaScript file and some places online are saying I need to import something? Im not sure!
Thanks

like image 685
user1346670 Avatar asked Aug 04 '26 01:08

user1346670


1 Answers

Try without quotes:

$('#here').html(testList);

-or-

$('#here').html(test.join('<br />'));

Another approach:

var html = '';                                    // string
$.each(test,function(i,val){                      // loop through array
    var newDiv = $('<div/>').html(val);           // build a div around each value
    html += $('<div>').append(newDiv.clone()).remove().html();   
       // get the html by
       //   1. cloning the object
       //   2. wrapping it
       //   3. getting that html
       //   4. then deleting the wrap
       // courtesy of (http://jquery-howto.blogspot.com/2009/02/how-to-get-full-html-string-including.html)
});

$('#here').html(html);

There might be more code in the latter, but it'll be cleaner in the long run if you want to add IDs, classes, or other attributes. Just stick it in a function and amend the jQuery.

like image 109
vol7ron Avatar answered Aug 06 '26 14:08

vol7ron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!