HTML and CSS Reference
In-Depth Information
</div>
<div id="second">
<h1>Second div</h1>
</div>
</body>
</html>
Of course, you also need to create the JavaScript file. Start with this
code in it:
var d = document.getElementById('first');
console.log(d.innerHTML);
If you load the page now, you'll see this in the console.
This happens because at the point where the JavaScript executes, no
element has the ID first . The JavaScript is executed as soon as it's ref-
erenced, in the <head> element. You need the JavaScript to await exe-
cution until after the document is loaded. Fortunately, there's an event
for just such a scenario.
Note that event handling code works very differently in older
versions of IE. We don't have room to go into the details here;
check the “Further reading'' section for more on the differences.
Wrap the code you want to run in a
function:
function go() {
var d = document
.getElementById('first');
console.log(d.innerHTML);
}
Then use the addEventListener
method to attach your function as a
handler for the window's load event:
window.addEventListener('load', go);
 
Search WWH ::




Custom Search