Display HTML in Javascript

I’m trying to display the elements in an array but doesn’t seem to work:

var myurl=new Array("google.com", "yahoo.com");

for (i=0;i<=myurl.length-1;i++){
   document.writeln("<a href='http://www.' +  myurl[i] +  target='_blank'>");
}

Not sure why it is not working??

The immediate problem is that your code has some messed up quote marks. It should look like this, instead:


document.writeln("<a href='http://www." + myurl[i] + "' target='_blank'>");

The next issue is that the links you’re creating don’t have any content in them. Here’s what the HTML will look like once it’s generated:


<a href='http://www.google.com' target='_blank'>
<a href='http://www.yahoo.com' target='_blank'>

What text do you want to use for the content of the link? The easiest solution is to just use the domain. To do that, change your JS to this:


document.writeln("<a href='http://www." + myurl[i] + "' target='_blank'>" + myurl[i] + "</a>");

That should give you HTML like this:


<a href='http://www.google.com' target='_blank'>google.com</a>
<a href='http://www.yahoo.com' target='_blank'>yahoo.com</a>

Another possible snafu is that, depending on when/how you use “document.writeln”, the rest of the content that already exists may be thrown away. (I’m not so sure about this, though. I might be making it up…)

you can use jquery templates. You simply write one-line template (the <a href…> markup) and then you call the template multiple times each with its own parameters