4

I really cannot understand why this does not work. I've tried couple of tricks but I just don't get it.

<html>
<head>
<script type="text/javascript">
alert('Hey');
    var vText = document.getElementById("results");
        vText.innerHTML = 'Changed';
        alert(vText.innerHTML);
</script>
</head>
<body>
<div id="results">
hey there
</div>
</body>
</html>
David Thomas
  • 249,100
  • 51
  • 377
  • 410
Ali
  • 5,338
  • 12
  • 55
  • 78
  • 1
    please post your HTML code, in best case provide an jsfiddle (jsfiddle.net) which makes it easier for us to help you – Raphael Michel Apr 14 '12 at 22:50
  • @rami Working on it, right now – Ali Apr 14 '12 at 22:51
  • @Hoque I've written this basically in textEdit and trying to view it on Safari – Ali Apr 14 '12 at 22:51
  • where did you keep that script? In a fuction? – Anil Apr 14 '12 at 22:52
  • http://jsfiddle.net/sK7GU/ check this fiddle . the snippet you shown us , have no issues..Everybody here guessing this can be the problem, unless showing your HTML file it's quiet hard to fix... – iDroid Apr 14 '12 at 22:52

5 Answers5

12

This is working as you can see here:

http://jsfiddle.net/gHbss/

It's important that you put the JavaScript after your HTML div container.

Nobita
  • 23,519
  • 11
  • 58
  • 87
4

The problem that you're facing is that the browser runs the JavaScript as it's encountered when rendering/processing the page. At this point it will alert() your message, but the relevant element, the #results div isn't present in the DOM, so nothing can be changed.

To address this, you can either place the script at the end of the page, just before the closing </body> tag, or run the code in the onload event of the body or window.

David Thomas
  • 249,100
  • 51
  • 377
  • 410
1

The script has to be placed after the div#results or executed onload, otherwise the element is still unknown when you try to access it.

Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
1

You need to call this script in onload event i.e

 window.onload=function(){
//your code
}
Nazmul
  • 7,078
  • 12
  • 51
  • 63
1
<html>
<head>
<script type="text/javascript">
function onloadCall()
{
    alert('Hey');
    var vText = document.getElementById("results");                                                 
    vText.innerHTML = 'Changed';
    alert(vText.innerHTML);
}
</script>
</head>
<body onload="onloadCall()">
    <div id="results">
    hey there
    </div>
</body>
</html>

Hope the above snippet shows you the fix

iDroid
  • 1,140
  • 1
  • 13
  • 30