简体   繁体   中英

Else-if element ID doesn't exist

I have a collection of clickable items. Each page generates new items based on what a user has chosen. I want to be able to run some code based on if a specific ID exists and if it doesn't exist I don't want it to run. This is what I have tried so far:

function pageLoad() {
    var ums = document.getElementById('DIVID').innerHTML;
    if(ums == "IN (INCHES)") {
        allFunctionsInvoked();
        }   
}

I'm getting this error message when the element doesn't exist:

Uncaught TypeError: Cannot read property 'innerHTML' of null

causing my program to freeze up. I've tried adding an else if statement to check if the ID is null, but still can't get a way to resolve it.

The .getElementById() method will return null if an element with the specified ID is not in the document.

Therefore you can check if the element is not null before retrieving the innerHTML property:

function pageLoad() {
    var element = document.getElementById('DIVID');

    if (element !== null && element.innerHTML == "IN (INCHES)") {
        allFunctionsInvoked();
    }   
}

As a side note, if you're just checking for a string of text, you could access the textContent property instead of the innerHTML property:

function pageLoad() {
    var element = document.getElementById('DIVID');

    if (element !== null && element.textContent === "IN (INCHES)") {
        allFunctionsInvoked();
    }   
}

You can check this value for being null :

function pageLoad() {
    var elem = document.getElementById('DIVID');

    if (elem === null) {
        console.log("No DIVID element.");
        return;
    }

    if (elem.innerHTML == "IN (INCHES)") {
        allFunctionsInvoked();
    }   
}

It is also possible to simply use !elem since null is falsy :

function pageLoad() {
    var elem = document.getElementById('DIVID');

    if (!elem) {
        console.log("No DIVID element.");
        return;
    }

    if (elem.innerHTML == "IN (INCHES)") {
        allFunctionsInvoked();
    }   
}    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM