Simple but error prone onclick error reporting

Keywords: Javascript

Uncaught TypeError: Cannot set property 'onclick' of null;

One sentence: "make sure that dom node rendering of click events is performed before JS!" Solve.

A native JS click event written by myself. JS code is written on the home page

<script type="text/javascript">
        var all_features = document.getElementById("all_features");
        var all_features_down = document.getElementById("all_features_down");

        all_features.onclick=function () {
            var price_content = document.getElementsByClassName("price_content");
            for (var i = 0; i < price_content.length; i++) {
                price_content[i].style.display = "none";
            }
            all_features.style.display = "none";
            all_features_down.style.display = "block";
        };
        all_features_down.onclick=function () {
            var price_content_down = document.getElementsByClassName("price_content");
            for (var i = 0; i < price_content_down.length; i++) {
                price_content_down[i].style.display = "block";
            }
            all_features.style.display = "block";
            all_features_down.style.display = "none";
        };
    </script>

The code doesn't have much to look at. The key is that the dom I clicked is not on the home page, and it's still rendered. Therefore, the above error is reported (although it's an error, it's insensitive to the user, and has no impact. When the user clicks the page, it can still operate normally).

But the programmer's no error:
Changed to

function trigger_switch_up() {
            var price_content = document.getElementsByClassName("price_content");
            for (var i = 0; i < price_content.length; i++) {
                price_content[i].style.display = "none";
            }
            all_features.style.display = "none";
            all_features_down.style.display = "block";
        };
        function () trigger_switch_down{
            var price_content_down = document.getElementsByClassName("price_content");
            for (var i = 0; i < price_content_down.length; i++) {
                price_content_down[i].style.display = "block";
            }
            all_features.style.display = "block";
            all_features_down.style.display = "none";
        };
<div onClick="trigger_switch_down()">Some Content</div>

Posted by Dutch MaFia-boy on Tue, 31 Mar 2020 06:56:38 -0700