1

im new to javascript and want to fill a div with some text. but it doesn't work. in the documentation this is the common way to do this. but, why doesn't work this for me?

my code is

<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
    document.getElementById('mytest').innerHTML="hey";
</script>
</head>
<body>

<div id="mytest"></div>

</body>
</html>
Jef
  • 29
  • 5
  • Asked and answered dozens of times. Search SO. –  Jul 12 '15 at 05:35
  • See http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element. –  Jul 12 '15 at 05:36
  • 1
    Quick tip: You can start debugging this sort of problem by opening your browser's developer tools and looking for errors. In Chrome, you can do this with Ctrl + Shift + i. You'll see this error: `Uncaught TypeError: Cannot set property 'innerHTML' of null`. That tells you that the result of `getElementById()` is not what you expected. – Ben Jul 12 '15 at 05:39

3 Answers3

3

You need to move your script to the end of your HTML. Right now, you're executing the script BEFORE your HTML has been parsed so the document is empty and thus document.getElemntById('mytest') does not find anything.

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

<div id="mytest"></div>

<script type="text/javascript">
    document.getElementById('mytest').innerHTML="hey";
</script>
</body>
</html>

See this other answer for a lot more discussion of this issue and other options if you don't want to move your <script> tag:

pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it

Community
  • 1
  • 1
jfriend00
  • 580,699
  • 78
  • 809
  • 825
1

thats because, in your document, the javascript is load at the first, but the div with the id mytest is not loaded at this moment.

you have 2 options to get this working:

first: say javascript to wait until the dom is loaded completly

window.onload=function(){
  document.getElementById('mytest').innerHTML="hey";
}

second:

put your script code at the bottom, so the javascript is loaded at least.

but i would prefer the first solution.

best

rob
  • 1,839
  • 7
  • 22
  • 32
1

Try in this way

<!DOCTYPE html>
<html>
<head>
<title></title>

</head>
<body>

<div id="mytest"></div>

</body>
<script type="text/javascript">
    document.getElementById('mytest').innerHTML="hey";
</script>
</html>

Js fiddle

Prasad Raja
  • 645
  • 1
  • 8
  • 33