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
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.button[0]?.innerText
(notice the ?) This first checks if button[0] exists