V
V
valitskiydmitriy2015-10-20 13:11:18
JavaScript
valitskiydmitriy, 2015-10-20 13:11:18

After checking for the presence of the element, Cannot read property?

Here they suggested how to check for the presence of an element, the error was resolved, but a new one appeared, here is the full code of the script:

window.onload = function () {
    var day = new Date,
        md = (new Date(day.getFullYear(), day.getMonth() + 1, 0, 0, 0, 0, 0)).getDate(),
        $month_name = "января февраля марта апреля мая июня июля августа сентября октября ноября декабря".split(" ");

        function set_select(a, c, d, e) {
            var el = document.getElementsByName(a)[0];

            if (!el) {
                console.warn('Element "' + a + '" not found');
                return;
            }

            for (var b = el.options.length = 0; b < c; b++) {
                el.options[b] = new Option(a == 'month' ? $month_name[b] : b + d, b + d);
            }

            el.options[e] && (el.options[e].selected = !0)
        }
    set_select("day", md, 1, day.getDate() - 1);
    set_select("month", 12, 1, day.getMonth());
    set_select("year", 50, day.getFullYear()-50, 50);


    var year = document.getElementById('year');
    var month = document.getElementById("month");

    function check_date() {
        var a = year.value | 0,
            c = month.value | 0;
        md = (new Date(a, c, 0, 0, 0, 0, 0)).getDate();
        a = document.getElementById("day").selectedIndex;
        set_select("day", md, 1, a)
    };

    if (document.addEventListener) {
        year.addEventListener('change', check_date, false);
        month.addEventListener('change', check_date, false);

    } else {
        year.detachEvent('onchange', check_date);
        month.detachEvent('onchange', check_date);
    }

}

Mistake:
Uncaught TypeError: Cannot read property 'addEventListener' of null

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2015-10-20
@alexey-m-ukolov

It's the same - you don't check if there are elements with id year and month on the page before attaching handlers to them.
The solution algorithm is very simple:
1. Look for all the places where the addEventListener function is used (well, it’s more correct, of course, to look at a specific file and line directly in the console).
2. See under what conditions the variable on which this method is called can be null.
3. Add the necessary checks.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question