0

In the below code why document.write works for array and not document.getElemntById?

    <!DOCTYPE html5>
<html>
    <head>
    </head>
    <body>

        <script>
        var arr = new Array("pro","pro1","pro2");
        for(var i =0 ;i<arr.length;i++)
        {
          document.getElementById("txt").innerHTML = arr[i];
          //document.write(arr[i]);
        }
        </script>
        <div id = "txt">
        </div>
    </body>
</html>
user3651606
  • 107
  • 4
  • 9

3 Answers3

1

Checking Scope

Consider placing your <script> tag at the end of your code (just prior to the </body> element or at least somewhere after your <div>) to ensure that it can see the element it needs to target :

<div id="txt"></div>
<script>
    // Your code here
</script>

This will ensure that your document.getElementById() function can "see" the element you are targeting and access it accordingly when needed.

Concatenate Your Values

While you absolutely could change your = to a += within your loop to continually concatenate to your contents :

document.getElementById("txt").innerHTML + = arr[i];

A better approach as mentioned by 4castle in his comment, would be to build a string within the loop and then set it after the final iteration to avoid issues with actually appending to the innerHTML property, which can cause some unexpected DOM issues :

var arr = new Array("pro","pro1","pro2");
var content = '';
for(var i =0 ;i<arr.length;i++){
      // Build your content
      content += arr[i];
}
// Now set it
document.getElementById("txt").innerHTML = content;

Avoid Looping with Array.join()

A better approach still would be to avoid the loop alltogether and to use the Array.join() function to concatenate and set your text without a loop :

var arr = new Array("pro","pro1","pro2");
document.getElementById("txt").innerHTML = arr.join('');

Example

enter image description here

<pre>Setting with Content</pre>
<div id="txt"></div>
<pre>Setting via Array.join()</pre>
<div id="txt2"></div>
<pre>document.write()</pre>
<script>
  var arr = new Array("pro", "pro1", "pro2");
  var content = '';
  for (var i = 0; i < arr.length; i++) {
    content += arr[i];
    document.write(arr[i]);
  }
  document.getElementById('txt').innerHTML = content;
  document.getElementById('txt2').innerHTML = arr.join('');
</script>
Community
  • 1
  • 1
Rion Williams
  • 74,820
  • 37
  • 200
  • 327
  • Currently in the process of changing just that :) – Rion Williams Jun 15 '16 at 13:50
  • Ok.. thanks it works by placing the div on top of the script tag and then concatenating the value but as I am new to javascript why then document.write works without concatenation ? – user3651606 Jun 15 '16 at 14:01
  • The `document.write()` function is going to simply write out whatever you pass in to the document itself. This gives it the appearance that it is concatenating to the same value, but in fact it's just adding each word which happen to appear next to one another. You can think of it as concatenating whatever you pass in to the document. – Rion Williams Jun 15 '16 at 14:02
0

It actually works properly, but you are overwriting your innerHTML over and over till end of array.

Use

document.getElementById("txt").innerHTML+ = arr[i];

to get your code working with minimal changes.

That said, this is not performant - as the DOM is slower than Javascript and you want to do as few DOM manipulations as possible for the best rendering experience. Not a problem in this specific case, but if you are doing this for a real-time app with 100s of elements, the page will crawl.

The best overall method is

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id = "txt">
</div>


<script>
var arr = new Array("pro","pro1","pro2");
var output='';
for(var i =0 ;i<arr.length;i++)
{
    output+= arr[i];
}
document.getElementById("txt").innerHTML=output;
</script>
</body>
</html>

But then you get into an issue of globally scoped variables. To resolve that, the real good answer for this specific issue is using an IIFE (Immediately Invoked Function Expression). Out of scope for this question though. We could go on and on about optimizations and best practices, but I'll stop here.

  • No, no, no, no. This is a terrible practice. With each `innerHTML +=` the browser has to reparse the DOM. Better use a string for accumulation and then assign the value after the loop. – 4castle Jun 15 '16 at 13:48
  • You can remove your downvote now. Massively improved answer. – user6387024 Jun 15 '16 at 15:20
0

In your code you are referring element by id from inline javascript. Instead you should write a separate javascript function and call it on some event. Below is sample function you can call on body onload event.

function myValue()
{
    var arr = new Array("pro","pro1","pro2");
    for(var i =0 ;i<arr.length;i++)
    {
      document.getElementById("txt").innerHTML = arr[i];
      //document.write(arr[i]);
    }
}
Raidri
  • 17,258
  • 9
  • 62
  • 65
  • It doesn't quite fix the problem, but this is good because the OP wasn't using an `onload` block. – 4castle Jun 15 '16 at 14:57