View Single Post
  #1 (permalink)  
Old February 25th, 2016, 03:22 PM
roberttan roberttan is offline
Registered User
Points: 10, Level: 1
Points: 10, Level: 1 Points: 10, Level: 1 Points: 10, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Feb 2016
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Cool Chapter 9 Exercise 1 - a better solution

This is a much DRY-er solution than the proposed answer which is monstrous.

Code:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Ch. 9 Exercise 1</title>
    <style>
        
        
    </style>

</head>
<body>
    


    <script>
        
        var array = [['Car', 'Top Speed', 'Price'],['Chevrolet', '120mph', '$10,000'], ['Pontiac', '140pmh', '$20,000']] // Creating a 2x2 data array which a loop will source from
        
        var table = document.createElement('table');
        document.body.appendChild(table); // Drew the main table node on the document
        
        for (var i = 0; i<3; i++) { 
            var tr = document.createElement('tr'); //Create 3 <tr> elements
            table.appendChild(tr); // Append to <table> node
            
            for (var j = 0; j<3; j++) {
                var tdElement = document.createElement('td');
                tdElement.innerHTML = array[i][j]; // Extract data from array to a placeholder variable
                tr.appendChild(tdElement); // Take string from placeholder variable and append it to <tr> node
            }
        }
        
        
        
        
        
    </script> 
    
</body>
    
</html>
Reply With Quote