Search code examples
javascriptundefinedsetintervalinnertext

Checking if innerText of class is defined or not


I have a js script, which is extracting the innertext of a class. Sometimes that class is not rendered on the webpage, so for that case, innertext comes undefined. I want to keep a check for this so that this error is omitted. This is the code that I wrote ->

function myfunc() {          
    var button = document.getElementsByClassName('myclass');
    if (button[0].innerText !== undefined) {   
        console.log(button[0].innerText);
        clearInterval(x);
    } 
}

var x = setInterval(function() {
    myfunc();
}, 1)

So for the cases when the class is not there on the page, I was getting an undefined error hence I want to check that. I used an if condition in the code by checking if it is !== undefined but that is not working. Can anyone suggest some other methods? The error that I was getting ->

Uncaught TypeError: Cannot read property 'innerText' of undefined

Solution

  • This doesn't work, because document.getElementsByClassName('myclass') returns 0 buttons, so button[0] is already undefined.

    You can solve this problem by using optional chaining:

    if(button[0]?.innerText !== undefined){
    

    The value on the left side is automatically undefined if something before the ? is undefined.

    If button[0] doesn't exist / is undefined, JS won't even try to get the innerText property.

    Or even easier

    Just check the length:

    if(button.length > 0) {