1

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
2
  • 1
    if(button[0]) {...} will probably work. At the moment you're trying to access the text of an element that doesn't exist for your condition.
    – Andy
    Commented Nov 9, 2021 at 7:13
  • Or try using button[0]?.innerText (notice the ?) This first checks if button[0] exists
    – cloned
    Commented Nov 9, 2021 at 7:16

2 Answers 2

3

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) {
0
0

You just need to check that button[0] exists before trying innerText on it. I cleaned it up a bit, but this should do the trick:

function checkForButton() {
   const button = document.querySelector('.myclass');
   if (button && button.textContent) {
     console.log(button.textContent);
     clearInterval(x);
   }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.