Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

page doesn't display anything

so I wrote a script to display 5 random arrays, but the page doesn’t display anything.
here’s the code:

<html>
  <head>
    <script>
      function start(){
        var arr(5),result;
        result=document.getElementById("arraying");
        result="<p>";
        for(var i=0; i<5;i++){
          arr[i]=Math.floor(Math.random()*10);
          result+="arr["+i+"]= "+arr[i]+"</p><p>";
        }
        result+="</p>";
      }
      window.addEventListener("load",start,false);
    </script>
  </head>
  <body>
    <div id="arraying"></div>
  </body>  
</html>

I tried removing result=document.getElementById and write document.getElementById.innerHTML=result in the end of the function but didn’t work. what’s the error?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You cannot use the same variable for different purposes at the same time. First you assign a DOM element to result, and immediately on the next line you overwrite result with a string.

Build a string htmlStr inside your loop, and when that is done, assign this string to result.innerHTML property:

function start() {
  let arr = [],
    result, htmlStr = '';
  result = document.getElementById("arraying");
  htmlStr += "<p>";
  for (let i = 0; i < 5; i++) {
    arr[i] = Math.floor(Math.random() * 10);
    htmlStr += "arr[" + i + "]= " + arr[i] + "</p><p>";
  }
  htmlStr += "</p>";
  result.innerHTML = htmlStr;
}
window.addEventListener("load", start, false);
<div id="arraying"></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading