0

I was working on a simple javascript code and I don't know what it is not working. Please tell me if you figure this out.

<!DOCTYPE html>
<html>
<head>
<script>
function displayText(){
var xa = document.getElementById('abcd').innerHTML;
xa+= 'asdf';
}

displayText();  
</script>
</head>
<body>
<div id="abcd"></div>
</body>
</html>
Himansh
  • 879
  • 9
  • 15

2 Answers2

6

innerHTML returns a String of the current contents of the element and not a pointer to it. So use this instead:

function displayText(){
  document.getElementById('abcd').innerHTML += 'asdf';
}

or

function displayText(){
  var el = document.getElementById('abcd'); 

  var xa = el.innerHTML;
  xa += 'asdf';

  el.innerHTML = xa;
}

Furthermore you can not call the function, before the element you are referring to is actually created. So move the call at the bottom of the body tag.

<!-- .... -->
<script>
  display();
</script>
</body>
Sirko
  • 72,589
  • 19
  • 149
  • 183
0

At the time the code runs the body (including your div) has not yet been parsed. getElementById('abcd') doesn't find anything at that time.

Either move your script element to the end of the body so that it runs after the body has been parsed, or call your displayText() function from an onload handler.

(And if you intend the new value in xa to be displayed in the same field you'll need to write it back to the element with document.getElementById('abcd').innerHTML = xa.)

nnnnnn
  • 147,572
  • 30
  • 200
  • 241