简体   繁体   中英

Cannot figure out where to load javascript file

HTML

<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <title>Game</title>
    <link rel="stylesheet" type="text/css" href="stylesheet.css">
    <script src="script.js"></script>   

</head>

<body>

    <div class="container">

    <table class="table ">
        <tr>
            <td id="1">a</td>           
            <td id="2">a</td>           
            <td id="3">a</td>           
            <td id="4">a</td>
        </tr>
        <tr>
            <td id="5">a</td>           
            <td id="6">a</td>           
            <td id="7">a</td>           
            <td id="8">a</td>
        </tr>
        <tr>
            <td id="9">a</td>           
            <td id="10">a</td>          
            <td id="11">a</td>          
            <td id="12">a</td>
        </tr>
        <tr>
            <td id="13">a</td>          
            <td id="14">a</td>          
            <td id="15">a</td>          
            <td id="16">a</td>
        </tr>
    </table>

    </div>


</body>

function startFunction() {
    var table = document.querySelector('#table');
    var table_cells = table.querySelectorAll('td');   
}


window.onload = function() {
  startFunction();
};

I keep getting an error of "uncaught typeError: cannot read property 'querySelectorAll' of null."

I think this has to do with the fact when I'm calling a function that tries to grab said element node before it exists perhaps?

I'm loading my Javascript file in the <head> section of my HTML file so I added a window.onload function to make sure everything is loaded before the page runs. However, I still keep getting this error.

Take a look at this line in your JavaScript:

var table = document.querySelector('#table');

The pound-sign indicates an ID , and so your javascript is looking for an element with the ID of "table".

But, if you look at your table, it doesn't have an ID; only class .

The solution is to give your <table> an ID of "table" so that the javascript properly finds it:

<table id="table">

The table is missing id attribute. Instead, it has class attribute. Fix by adding id

<table class="table" id="table">

Or modify your query selector to select by class:

var table = document.querySelector('.table');

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