質問

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.

他のヒント

You are calling the function, not assigning it.

window.onload = initP();

needs to be

window.onload = initP;

The downside to the way you are attaching events is that if anything else before this registerd to the onload event, you will override it. Better to use element.addEventListener

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top