Ok. I need fresh eyes because I’m still on this s***d problem for one hour!
Here is my simple HTML code (testssio.html) that include javascript script:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var ssio = document.getElementById('ssio');
ssio.html = "it finally works!";
</script>
</head>
<body>
<div id="ssio"></div>
</body>
</html>
But it doesn’t work! Using the debugger, I get:
Uncaught TypeError: Cannot set property 'html' of null /testssio/:6
Does anyone get it? I know it’s not the correct place to look for debugging help, but I’ll be crazy if I don’t get it! So please, any help?
Tahnks in advance.
The reason for this is that scripts in the head load before the page is rendered. This means your content is not yet rendered and therefore not a part of
document.If you want to see this work, try moving your script below the element renders, like this:
A more standardized way of doing this is with events. Many people use jQuery but it can be done with plain js. This would mean changing your script like this:
This way you can still leave it in the
<head>.Also, using
.htmlis from jQuery. It is generally used as.html(content). If you want to use the plain javascript version use.innerHTML = content.I mention jQuery so much because it is a highly used API. This quote is from their site: