1

I tried to run the following code which showed up a blank screen

function make() {
    for (var i = 1; i <= 8; i++) {
        var j = "d" + i;
        var c = document.createElement("div");
        c.setAttribute("id",j);
        document.getElementById(j).innerHTML = 'Hello<br>';
    }
}
#d1 {font-family: 'Cinzel';}
#d2 {font-family: 'Cookie';}
#d3 {font-family: 'Great Vibes';}
#d4 {font-family: 'Monoton';}
#d5 {font-family: 'Orbitron';}
#d6 {font-family: 'Pacifico';}
#d7 {font-family: 'Righteous';}
#d8 {font-family: 'Sacramento';}
<!DOCTYPE html>
<html>
<head>
<title>Logo</title>
<link href="https://fonts.googleapis.com/css?family=Cinzel|Cookie|Great+Vibes|Monoton|Orbitron|Pacifico|Righteous|Sacramento" rel="stylesheet">
</head>
<body onload="make()">
</body>
</html>

In the above snippet, I have used a javascript function where i have created 8 elements and seperated each with a line-break . But, Unfortunately, the line containing the 'innerHTML' throws a type error and the rest of the code does not generate the desired output.
Please do help me out!
Thank You

St.Over.Guest21
  • 158
  • 1
  • 11

2 Answers2

2

You're missing this very important line document.body.appendChild(c);

You've to insert the element into the document tree using appendChild or insertBefore because the element must be inserted into the DOM before you try to get it by document.getElementById(j)

<!DOCTYPE html>
<html>

<head>
  <title>Logo</title>
  <link href="https://fonts.googleapis.com/css?family=Cinzel|Cookie|Great+Vibes|Monoton|Orbitron|Pacifico|Righteous|Sacramento" rel="stylesheet">
  <style type="text/css">
    #d1 {
      font-family: 'Cinzel';
    }
    
    #d2 {
      font-family: 'Cookie';
    }
    
    #d3 {
      font-family: 'Great Vibes';
    }
    
    #d4 {
      font-family: 'Monoton';
    }
    
    #d5 {
      font-family: 'Orbitron';
    }
    
    #d6 {
      font-family: 'Pacifico';
    }
    
    #d7 {
      font-family: 'Righteous';
    }
    
    #d8 {
      font-family: 'Sacramento';
    }
  </style>
</head>

<body onload="make()">
  <script type="text/javascript">
    function make() {
      for (var i = 1; i <= 8; i++) {
        var j = "d" + i;
        var c = document.createElement("div");
        c.setAttribute("id", j);
        document.body.appendChild(c);
        document.getElementById(j).innerHTML = 'Hello<br>';
      }
    }
  </script>
</body>

</html>
Always Sunny
  • 29,081
  • 6
  • 43
  • 74
0

Instead of that line:

document.getElementById(j).innerHTML = 'Hello<br>';

Try this:

c.textContent = 'Hello';

And as comments and answers - you should insert the element into the document tree using appendChild with appendChild(c);

A. Meshu
  • 3,326
  • 2
  • 15
  • 29