0

Hi trying to understand and fix the console error I'm getting when running the following code full code here

for(var i = 0 ; i <= paragraphs.length ; i++){
  if( i === 0 ){
    continue
  }
  paragraphs[i].classList.add('hide')
}

The error reads

Cannot read property 'classList' of undefined

I found this explanation on reddit but I was not sure how it had been fixed?

Many thanks in advance

2
  • 3
    you could save the if clause by starting from 1. Commented Feb 17, 2017 at 8:39
  • 1
    In JavaScript arrays (and array-like objects) are zero-indexed: the first element of an array is at index 0, and the last element is at the index equal to the value of the array's length property minus 1. (ref.) Commented Feb 17, 2017 at 8:41

2 Answers 2

2

You are out of your array on your loop.

Do this :

for(var i = 0 ; i < paragraphs.length ; i++)

Instead of

for(var i = 0 ; i <= paragraphs.length ; i++)

You can optimized your loop to begin on the second item directly ("i = 1 instead of "i =0")

Sign up to request clarification or add additional context in comments.

Comments

2

Your loop exceeds the number of your paragraphs to solve it you must:

1 - paragraphs.length-1

or

2 - i < paragraphs.length

var paragraphs = document.getElementsByTagName('p'),
    firstParagraph = paragraphs[0],
    link = document.createElement('a');
    link.innerHTML = 'Show more';
    link.setAttribute('class' , 'link');
    link.setAttribute('href' , '#');
    firstParagraph.appendChild(link);
        for(var i = 0 ; i <= paragraphs.length-1 ; i++){
          if( i === 0 ){
            continue
          }
          console.log("hellp",paragraphs[i]);
          paragraphs[i].classList.add('hide')
        }

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.