V
V
valitskiydmitriy2015-10-21 14:47:53
JavaScript
valitskiydmitriy, 2015-10-21 14:47:53

Checking for elements before executing js script?

There is this piece of code

function check_date() {
        var a = year.value | 0,
            c = month.value | 0;
            var ch = document.getElementsByName('month','year');
            if (!ch) {
        console.warn('Element "' +ch + '" not found');
        return;
    }

        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);
    }

}

When loading all pages except the registration page, an error, null, was advised to check for the presence of elements, wrote according to the model that was, but still does not work, double-checked and anyway, what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Kravchenko, 2015-10-21
@mydearfriend

var empty = document.getElementsByName('not-existing-name');
console.log(empty, !!empty); 
//посмотрим что там 
//и что получится при приведении к булеву типу 
//(как в проверке if)
//[], true

how to fix?
if (!ch.length) {
  console.warn('Element "' +ch + '" not found');
  return;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question