检查是否定义了 class 的 innerText

Checking if innerText of class is defined or not

我有一个js脚本,它正在提取一个class的内部文本。有时 class 不会在网页上呈现,因此对于这种情况,innertext 未定义。我想对此进行检查,以便省略此错误。 这是我写的代码 ->

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)

因此,对于页面上不存在 class 的情况,我遇到了一个未定义的错误,因此我想检查一下。我通过检查它是否为 !== undefined 在代码中使用了 if 条件,但这不起作用。任何人都可以建议一些其他方法吗?我遇到的错误 ->

Uncaught TypeError: Cannot read property 'innerText' of undefined

您只需在尝试 innerText 之前检查 button[0] 是否存在。我稍微清理了一下,但这应该可以解决问题:

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

这不起作用,因为 document.getElementsByClassName('myclass') returns 0 个按钮,所以 button[0] 已经未定义。

您可以使用可选链接解决这个问题:

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

如果 ? 之前的内容未定义,则左侧的值自动未定义。

如果 button[0] 不存在/未定义,JS 甚至不会尝试获取 innerText 属性.

或者更简单

检查一下长度:

if(button.length > 0) {