I have several functions running in my main js file and after I added two lines to one of them, this error appears. The odd thing is, the error references a variable in one of the other functions which is entirely unrelated to the one being called.
Here is the function that I changed:
window.onresize = function(){
var timeOut = null;
if(timeOut != null) clearTimeout(timeOut);
setTimeout(expandWrapper, 500);
}
var expandWrapper = function(){
//var eContent = document.getElementById("content");
var eContent = document.getElementById("main-content");
var eMainContent = document.getElementById("column-1");
var elayoutArea = document.getElementById("layout-column_column-1");
var eFooter = document.getElementById("footer");
//var dScrollb = $(".dataTables_scrollBody");
var leftWrapper = document.getElementById("left-links-wrapper");
var contentEnd = eMainContent.clientHeight + eMainContent.offsetTop;
if(document.documentElement.clientHeight >= (eContent.offsetTop + elayoutArea.clientHeight + eFooter.clientHeight)){
eMainContent.style.height = document.documentElement.clientHeight - eContent.offsetTop - eFooter.clientHeight -1 + "px";
added line--> leftWrapper.style.height = document.documentElement.clientHeight - eContent.offsetTop - eFooter.clientHeight -1 + "px";
//console.log("primary condition");
} else {
eMainContent.style.height = ($(window).height()); //elayoutArea.clientHeight + "px";
added line-->leftWrapper.style.height = eMainContent.offsetHeight + "px";
//console.log("fallback");
}
}
I’ve pointed out the two added lines, located in the if statement and beginning with “leftWrapper.style.height“. Incidentally, while eMainContent element appears on all pages, leftWrapper element only appears on certain pages and the error appears only on those page where leftWrapper does not exist.
I’m thinking this is where the problem lies: the javascript flips out because it can’t perform the action I’ve requested on an element that does not exist on a particular page.
Assuming this is the problem, how could I rewrite this to alleviate this error but modify leftWrapper on the pages where it exists?
The problem, as you point out, is that calling
getElementByIdwill return null if you pass in an identifier not present in the DOM.For cases like these where you’re working with an object that could be null or undefined, you can simply do the following:
This could also be shortened to:
taking advantage of the short-circuiting of the
&&operator.One caveat worth noting is that this won’t behave as you’d expect for all variables.
0and''are also falsey values. If you know you’ll be dealing with strings or numbers, you can instead do something like: