简体   繁体   中英

External JS Doc Not Working

So I'm practicing my JavaScript skills with a simple little script that will change the heading size and color upon a click. When I run the JS from within the HTML doc within script tags it works perfectly fine, but when I run the page in my browser, the console gives me the error: "Uncaught TypeError: Cannot read property 'addEventListener' of null - (anonymous function) @ practice.js:13"

HTML Code:

<!DOCTYPE html>
<html>
<head>
    <title>Javascript</title>
    <link rel="stylesheet" href="main.css">
    <script src="practice.js"></script>
</head>

<body>
    <h1 id="main-heading">Hello</h1>

    <p class="para">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
    consequat.</p>

    <p class="para">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua.</p>
</body>

</html>

CSS Code:

.red-text {
        color: red;
        font-size: 60px;
        transition: 5s;
    }

#main-heading {
    font-size: 40px;
}

JavaScript Code:

// Creates "h" var, containing the main heading

var h = document.getElementById("main-heading");

// Creates a function that adds .red-text class to main heading

var addRedClass = function() {
    h.className = h.className + " red-text";
};

// Activates the addRedClass function upon mouseover

h.addEventListener('click', addRedClass);

Help?!

you should place your javascript codes at the bottom of the page like this:

<!DOCTYPE html>
<html>
<head>
    <title>Javascript</title>
    <link rel="stylesheet" href="main.css">
</head>

<body>
    <h1 id="main-heading">Hello</h1>

    <p class="para">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
    consequat.</p>

    <p class="para">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua.</p>
    <script src="practice.js"></script>
</body>

</html>

because when you call document.getElementById("main-heading") in the head, there is no main-heading element in the document, on head is loaded, so you should place your javascript code at the bottom or use window.load function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM