SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast
    Join Date
    Jun 2010
    Posts
    34
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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:
    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.
    Code:
    <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>

  2. #2
    Barefoot on the Moon! silver trophy Force Flow's Avatar
    Join Date
    Jul 2003
    Location
    Northeastern USA
    Posts
    4,606
    Mentioned
    56 Post(s)
    Tagged
    1 Thread(s)
    A few changes:

    Code:
    <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.
    Visit The Blog | Follow On Twitter
    301tool 1.1.5 - URL redirector & shortener (PHP/MySQL)
    Can be hosted on and utilize your own domain

  3. #3
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,702
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by Force Flow View Post
    A few changes:
    A few changes

    • 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


    http://jsfiddle.net/pmw57/NkzUN/
    Code html4strict:
    <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.

    http://jsfiddle.net/pmw57/NkzUN/1/
    Code javascript":
    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/
    Code javascript:
    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/
    Code javascript:
    ...
    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/
    Code javascript:
    (function (window, document, undefined) {
        ...
        updateWithLinks('info', ['google.com', 'yahoo.com']);
    }(this, this.document));
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •