0

Below is a very simple function that will set the text content of a DOM element.

const display = (el, value) => {
  el.textContent = value;
};

display(document.getElementById('element1'), 'One');
display(document.getElementById('element2'), 'Two');
<span id="element1" />
<span id="element2" />

Strangely enough, when invoked the second time, the function will error out with the familiar:

Uncaught TypeError: Cannot set property 'textContent' of null

At first I thought that the problem might be due to the fact that the second element might not have been loaded yet at the time of execution, but:

  • The script is inlined at the end of the body tag, so all DOM elements should have been loaded.
  • Invoking the function only on the second element correctly prints Two.
  • Replacing the calls to display() with console.log(document.getElementById('element1')) and console.log(document.getElementById('element2')) successfully prints out both elements.
  • Changing the order of the two calls will still only display One, but no error occurs.

So I'm stumped. The problem presents itself both in a stacksnippet and when loaded as a separate HTML page. It occurs in both current Firefox and Chrome.

Am I missing something very obvious here? Can anyone tell me what's going on?

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156

1 Answers1

2

const display = (el, value) => {
  el.textContent = value;
};

display(document.getElementById('element1'), 'One');
display(document.getElementById('element2'), 'Two');
<span id="element1"></span>
<span id="element2"></span>

if you correct the span tags then it works correctly. so you close the span tag correctly.

Inus Saha
  • 1,918
  • 11
  • 17