Document.getElementById?

I’m trying convert document.write to document.getElementById
but it is not working and I can’t seem to figure it out.

This is my original code:

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

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

I would like to convert to document.getElementById but it doesn’t work.

<HTML>
<HEAD>
<TITLE>Test Input</TITLE>
<script type="text/javascript">

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

   document.getElementById('info').innerHTML = "<table border=1><tr><td>";

   for (i=0;i<=myurl.length-1;i++){
      document.getElementById('info').innerHTML += "<tr><td><a href='http://www." +  myurl[i] + " target='_blank'>"+ myurl[i]+"</a></tr></td>";
   }
   document.getElementById('info').innerHTML = "</tr></td></table>";
</script>
</HEAD>

<BODY>


<p id="info"></p>

</BODY>
</HTML>

A few changes:

<HTML>
<HEAD>
<TITLE>Test Input</TITLE>
<script type="text/javascript">

   var myurl = new Array("google.com", "yahoo.com"); 
   var mytable ='';
   
   window.onload = function() { 

        document.getElementById('info').innerHTML += '<table border="1"><tr>';
        mytable+='<table border="1"><tr>';
        
       for(var i=0; i<myurl.length; i++){
          mytable+='<td><a href="http://' +  myurl[i] + '" target="_blank">'+ myurl[i]+'</a></td>';
       }
       
       mytable+='</tr></table>';
       document.getElementById('info').innerHTML=mytable;
   
   }
</script>
</HEAD>

<BODY>


<div id="info"></div>

</BODY>
</HTML>

The onload function is key because the browser reads an html file from top to bottom. In the javascript section, you can’t reference an ID for something that hasn’t been created yet further down on the page. So, what the onload function does is wait until the page has been read, then executes the javascript code in the onload function.

As for the other things, a few minor syntax issues (note–when you are creating strings, pay attention to which quotes you use).

When you write innerHTML, it’s usually best to store everything in a variable until you’re ready to write it to the page. Otherwise, you sometimes get strange rendering issues when you try feeding in html a piece at a time without full and complete opening and closing tags.

A few changes :slight_smile:

[list][]Lowercase for tag names has been the practice since HTML 4.01 was released in 1999
[
]Declare all variables at the start of the function or section of code, to prevent the bad habit temptation of declaring them throughout the code
[]The new Array() is a Java-like constructor which we tend to stay away from now - use [] instead
[
]Remove the first innerHTML statement as it’s a duplicate and a waste
[]Pick a standard for string literals. Commonly double quotes are used for HTML quotes and single quotes for JavaScript quotes
[
]Use a consistent spacing of one space either side of operators for ease of readability[/list]


<html>
<head>
<title>Test Input</title>
</head>

<body>
<div id="info"></div>

<script type="text/javascript">
var info = document.getElementById('info'),
    myurl = ['google.com', 'yahoo.com'],
    mytable = '',
    i;

mytable += '<table border="1"><tr>';
for (i = 0; i < myurl.length; i++) {
    mytable += '<td><a href="http://' + myurl[i] + '" target="_blank">' + myurl[i] + '</a></td>';
}
mytable += '</tr></table>';

info.innerHTML = mytable;
</script>
</body>
</html>

Then we can move different parts of the code out to separate functions, to help simplify things.


function createLinks(urls) {
    var links = [],
        i;
    for (i = 0; i < urls.length; i++) {
        links[i] = '<a href="http://' + urls[i] + '" target="_blank">' + urls[i] + '</a>';
    }
    return links;
}
function createTable(links) {
    var table = '<table border="1"><tr>',
        i;
    for (i = 0; i < links.length; i++) {
        table += '<td>' + links[i] + '</td>';
    }
    table += '</tr></table>';
    return table;
}

var info = document.getElementById('info'),
    myurl = ['google.com', 'yahoo.com'],
    links = createLinks(myurl);
info.innerHTML = createTable(links);

After which we can simplify things even further by using the Array.forEach() method in the functions

http://jsfiddle.net/pmw57/NkzUN/2/


function createLinks(urls) {
    urls.forEach(function (link, index, array) {
        array[index] = '<a href="http://' + link + '" target="_blank">' + link + '</a>';
    });
    return urls;
}
function createTable(links) {
    links.forEach(function (link, index, array) {
        array[index] = '<td>' + link + '</td>';
    });
    return '<table border="1"><tr>' + links + '</tr></table>';
}
...

We can even move the last part in to its own function, so that we just pass the ‘info’ and sites to the function

http://jsfiddle.net/pmw57/NkzUN/3/


...
function updateWithLinks(id, sites) {
    var links = createLinks(sites),
        html = createTable(links);
    document.getElementById(id).innerHTML = html;
}

updateWithLinks('info', ['google.com', 'yahoo.com']);

And lastly we could wrap our code so that we don’t inadvertently clobber other code that uses the same variable names that we use.

http://jsfiddle.net/pmw57/NkzUN/4/


(function (window, document, undefined) {
    ...
    updateWithLinks('info', ['google.com', 'yahoo.com']);
}(this, this.document));