Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: Cannot set property 'onclick' of null onclick not working

see below is my javascript,

<script type="text/javascript">
document.getElementById('auth').onclick=change;
function change(){
    this.className="account_holder";
}
</script>

html is

<td id="auth" class="authorised_reportericon" >
                        <a href="{% url incident.views.authorised_reporter %}">
                        <p align="center" style="color:black;font-size:16px;">Authorised Reporters</p></a>
                    </td>

I assigned td's id for onclick,but it is trowing error as Uncaught TypeError: Cannot set property 'onclick' of null

like image 299
user2086641 Avatar asked Nov 21 '25 17:11

user2086641


2 Answers

Put document.getElementById('auth').onclick=change; inside of window.onload, like:

window.onload = function () {
    document.getElementById('auth').onclick=change;
};

According to the error you're getting, I'm guessing your Javascript is executed before your relevant HTML is rendered, meaning the element with the id "auth" isn't found. Putting it in an event where the whole DOM is ready should fix the problem.

Demo: Here

like image 116
Ian Avatar answered Nov 23 '25 07:11

Ian


Most likely you've placed the script in the head of the document, which means it's running before the rest of the page has been rendered.

Instead, move it inside the body, to the very bottom, just before the closing </body> tag.

<!doctype html>
<html>
    <head>
        <title>my page</title>
    </head>
    <body>

        <!-- your page content -->

        <!-- your script -->
        <script type="text/javascript">
        document.getElementById('auth').onclick=change;
        function change(){
            this.className="account_holder";
        }
        </script>
    </body>
</html>

Now the elements will be available before the script runs. This is because the page renders in order from top to bottom, and scripts block the rendering when loading.

So when the script is in the head, it prevents the rest of the page below it from rendering until the script is complete, which means the "auth" doesn't yet exist.

Using this positioning technique of the script toward the end allows it to run potentially much sooner than waiting for a window.onload event.

like image 27
yowza Avatar answered Nov 23 '25 05:11

yowza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!