Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Does not change the div innerHTML

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>
like image 630
Ali Avatar asked Dec 02 '22 00:12

Ali


2 Answers

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.

like image 83
Nobita Avatar answered Dec 04 '22 10:12

Nobita


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.

like image 27
David Thomas Avatar answered Dec 04 '22 10:12

David Thomas