Search code examples
javascripthtmldom

How to avoid the nan error in javascript?


I need the height of several containers to be subtracted from a number (for example 1000) at the same time this number must be a css value (in this case 1000px). But when I add the height of the containers and subtract it from the number 1000 I get the NaN error. I need an answer without the use of jquery. This is the code:

let carouselHeight = document.getElementById("carouselExampleAutoplaying").offsetHeight;
let cardHeaderHeight = document.getElementById("cardHeaderDiv").offsetHeight;
let navbarHeight = document.getElementById("navDiv").offsetHeight;
let bannerHeight = document.getElementById("topBannerDiv").offsetHeight;
let CardBody = document.getElementById('CardBody');
CardBody.setAttribute('style', 'height: ' + 1000 - bannerHeight - navbarHeight - cardHeaderHeight - carouselHeight + 'px');

Solution

  • This is concatenating strings and trying to perform math on strings:

    'height: ' + 1000 - bannerHeight - navbarHeight - cardHeaderHeight - carouselHeight + 'px'
    

    Specifically, it's first doing 'height: ' + 1000 which results in the string value 'height1000', then it's trying to do: 'height1000' - bannerHeight, the result of which is not a number because you can't subtract from a string.

    For example:

    const bannerHeight = 1;
    const navbarHeight = 2;
    const cardHeaderHeight = 3;
    const carouselHeight = 4;
    const result = 'height: ' + 1000 - bannerHeight - navbarHeight - cardHeaderHeight - carouselHeight + 'px';
    console.log(result);

    But you intended this part to be math:

    1000 - bannerHeight - navbarHeight - cardHeaderHeight - carouselHeight
    

    Perform the math first, then use the result in your string. Which you could do as a separate operation, or by simply wrapping the expression in parentheses to control the order of operations:

    'height: ' + (1000 - bannerHeight - navbarHeight - cardHeaderHeight - carouselHeight) + 'px'
    

    For example:

    const bannerHeight = 1;
    const navbarHeight = 2;
    const cardHeaderHeight = 3;
    const carouselHeight = 4;
    const result = 'height: ' + (1000 - bannerHeight - navbarHeight - cardHeaderHeight - carouselHeight) + 'px';
    console.log(result);