2

Here is piece of code i am getting an error in the console, can anyone point out where i am doing it wrong ? thanks in advance.

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)
Martin Adámek
  • 12,431
  • 5
  • 25
  • 47
Junaid
  • 31
  • 1
  • 7
  • check for null/undefined before accessing nextSibling – awd Oct 14 '17 at 12:39
  • _"check if nextSibling is textnode (whitespace) - if so get next next sibling"_ -> [.nextElementSibling](https://developer.mozilla.org/en-US/docs/Web/API/NonDocumentTypeChildNode/nextElementSibling) – Andreas Oct 14 '17 at 12:42

2 Answers2

1

The error means that the element you are looking for (with class visible) is not existing when the code is ran. Maybe you are running the code too early (before DOM is parsed).

Try adding simple if condition like this:

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

if (!visibleWord) {
    return;
}

// continue with the code... 
var nextWord = visibleWord.nextSibling;
Martin Adámek
  • 12,431
  • 5
  • 25
  • 47
0

is means there is no visibleWord so if that is the case you could return like so:

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)
caramba
  • 19,727
  • 15
  • 78
  • 118