I keep getting TypeError: Cannot read property 'forEach' of null
in my Javascript because I'm not checking for null after a document.querySelectorAll()
call.
Is there a way to create a special forEach()
on the Javascript null
object, and make it do nothing, thereby eliminating the error? Or, can we replace the forEach()
that I use with .forEach2()
so that forEach2()
won't do anything on a null
?
For example:
var $ = s => document.querySelectorAll.bind(document)(s).length > 1 ? document.querySelectorAll.bind(document)(s) : document.querySelector.bind(document)(s);
$('FOOTER EM').forEach(function(el,i){
console.log(el);
});
The above is generating an error for me if there is no EM under FOOTER, such as at runtime I sometimes add some.