0

I was told that it's best to avoid using document.write() as much as possible. So how would you suggest I handle this code

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Debug</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script>
    function writeTimesTable(num) {
      for(let i = 1; i < 13; i++ ) {
        let writeString = i + " * " + num + " = ";
        writeString = writeString + (i * num);
        writeString = writeString + "<br />";
        document.write(writeString);
      }
    }

  </script>
</head>
<body>
  <script>
    for(let i = 1; i <= 13; i++ ) {
      document.write("<p>")
      writeTimesTable(i) 
      document.write("</p>")

    }
  </script>
</body>
</html>

I've tried a innerHTML but I keep getting an undefined

This is the code I used after

function writeTimesTable(num) {
  for(let i = 1; i < 10; i++ ) {
    let writeString = i + " * " + num + " = ";
    writeString = writeString + (i * num);
    writeString = writeString + "<br />";
    document.write(writeString);
  }
}


function newTable() {
  for(let i = 1; i <= 10; i++ ) {
    let para = document.getElementById("paragraph");
    para.innerHTML = writeTimesTable(i)    

  }
}
Pat Lopes
  • 51
  • 1
  • 7
  • Hi, is not about efficiency, it depends on what technologies you are using, as far as I can see you are only using html and javascript, so you have a few options to choose from, it also depends on your needs, but for this post your example seems quite basic, it is ok if your starting to learn javascript and you should not be worried about performance, at the end the performance comes from the browser and not the javascript instruction itself. – Jonnathan Q Mar 16 '18 at 20:07
  • DOM manipulation as exposed by @bukharim96 is a nice approach as you will have a "cleaner" code avoiding a mixture of javascript and html code. Also it will give you the ability to update/modify page regions without the need to process the whole page. – Jonnathan Q Mar 16 '18 at 20:08
  • @JonnathanQ I tried this code `function newTable() { for(let i = 1; i <= 10; i++ ) { let para = document.getElementById("tag"); para.innerHTML = writeTimesTable(i) } } newTable();` but keep getting an undefined in my div element – Pat Lopes Mar 16 '18 at 20:55
  • In order to use **document.getElementById("paragraph");** you need a previously declared element (like a div) on your html file... with its proper id attribute set to *paragraph* – Jonnathan Q Mar 16 '18 at 22:11
  • @JonnathanQ Yes I know I did that and still get an undefined when I try to insert that logic inside the div element – Pat Lopes Mar 16 '18 at 22:13
  • is your code updated on the post?? review https://jsfiddle.net/jquijano82/L2hce2g6/6/ – Jonnathan Q Mar 16 '18 at 22:23

1 Answers1

0

Just use element.innerHTML = content i.e. DOM Manipulation

baeyun
  • 228
  • 1
  • 6