I am trying some basic Javascript with selecting elements and tags but it's giving me issues. Specifically I get this error in the dev tools using chrome or firefox:
Uncaught TypeError: Cannot call method 'getElementsByTagName' of null
The weird thing is that when I type the javascript command into the console on the browsers, it works without a problem. (Selecting the p tags within wrapper div)
This is my html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<link rel="stylesheet" href="default.css" />
<script type="text/javascript" src="selection.js"></script>
</head>
<body>
<div id="wrapper">
<p>Hello, this is a paragraph</p>
<p>Another one!</p>
<p>This is yet another paragraph</p>
</div>
</body>
</html>
Then my Javascript is:
window.onload = initP();
function initP() {
var para = document.getElementById('wrapper').getElementsByTagName('p');
}
Try with:
window.onload = initP;
instead of
window.onload = initP();
as you are calling the function and not assigning it.