0

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.

3
  • Where are you trying to output the html? Commented Dec 13, 2010 at 18:34
  • 2
    Trying to chain a document.write() call with .html() (which is a jQuery thing) makes absolutely no sense. Why are you using document.write() at all? Commented Dec 13, 2010 at 18:38
  • how im going to print without document.write() ? Commented Dec 13, 2010 at 18:48

4 Answers 4

6

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/

Sign up to request clarification or add additional context in comments.

Comments

1

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.

 }

});

1 Comment

This IS doing exactly what you need. Are you really even using jQuery?
1

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);

Comments

0

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]);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.