未捕获的TypeError:无法读取属性' nextSibling'未定义的

时间:2017-10-14 12:35:15

标签: javascript jquery

这是我在控制台中收到错误的一段代码,有人能指出我做错了吗?提前谢谢。

var intervalID = setInterval(function() {
    // every 4 seconds execute following
    var visibleWord = document.getElementsByClassName('visible')[0],
    nextWord = visibleWord.nextSibling;

    // check if nextSibling is textnode (whitespace) - if so get next next sibling. 
    if (nextWord.nodeType == 3) nextWord = nextWord.nextSibling;

    // if there is a next node 
    if (!(nextWord == null)) {
        visibleWord.setAttribute('class', 'hidden');
        nextWord.setAttribute('class', 'visible');
    } else {
        clearInterval(intervalID);
    }
}, 4000)

2 个答案:

答案 0 :(得分:1)

错误意味着在运行代码时,您要查找的元素(使用类visible)不存在。也许你过早地运行代码(在解析DOM之前)。

尝试添加简单的if条件:

var visibleWord = document.getElementsByClassName('visible')[0];

if (!visibleWord) {
    return;
}

// continue with the code... 
var nextWord = visibleWord.nextSibling;

答案 1 :(得分:0)

表示没有visibleWord所以如果是这样的话,你可以这样返回:

var intervalID = setInterval(function() {
// every 4 seconds execute following
var visibleWord = document.getElementsByClassName('visible')[0],
    if(null == visibleWord) {    // added this line
        return;                  // and this line
    }                            // and this line
    nextWord = visibleWord.nextSibling;
// check if nextSibling is textnode (whitespace) - if so get next next sibling. 
if (nextWord.nodeType == 3) nextWord = nextWord.nextSibling;
// if there is a next node 
if (!(nextWord == null)) {
    visibleWord.setAttribute('class', 'hidden');
    nextWord.setAttribute('class', 'visible');
} else {
    clearInterval(intervalID);
}
}, 4000)