t0s
t0s

Reputation: 1221

print array with js and add html with jQuery

i want to print an array with js and just add to every element some data with html()

the code i use is :

<script type="text/javascript">

$(document).ready(function() {
 var testArray = ["test1","test2","test3","test4"];

 for(var i=0;i<testArray.length;i++){
 document.write(" " +testArray[i]+"<br />").html("is the best");
 }
});

</script>

but it doesnt works.

Upvotes: 0

Views: 17513

Answers (4)

eriksv88
eriksv88

Reputation: 3528

HTML:

<div id="myDIV"></div>

JS:

$(document).ready(function() {
    var testArray = ["test1","test2","test3","test4"];
    var vPool="";
    jQuery.each(testArray, function(i, val) {
        vPool += val + "<br /> is the best <br />";
    });

    //We add vPool HTML content to #myDIV
    $('#myDIV').html(vPool);
});

Update: Added demo link: http://jsfiddle.net/aGX4r/43/

Upvotes: 6

joksnet
joksnet

Reputation: 2325

First. document.write it's not a good practice.

Then, you code have a little error: Function (as in document.write) doesn't have html method. Thats a jQuery method.

So, in order to print the array in the body, you could do:

$('p').html(["test1","test2","test3","test4"].join('<br />')).appendTo(document.body);

Upvotes: 1

halfpastfour.am
halfpastfour.am

Reputation: 5933

Syntax problem mate!

Let me get that for you!

// first create your array
var testArray = ["test1", "test2", "test3", "test4"];

// faster ready function
$(function(){

 for( var i=0; i<testArray.length; i++ ) {

  current = testArray[i] + '<br />' + 'is the best'; // this is a string with html in it.

  $(current).appendTo("body"); // add the html string to the body element.

 }

});

Upvotes: 1

Kyle
Kyle

Reputation: 4366

It's a little difficult to tell what you want to do, but if you want to append to an element in your DOM, use jQuery.append();

for(var i=0;i<testArray.length;i++) {
    jQuery('#mydiv').append(testArray[i]);
}

Upvotes: 0

Related Questions