Mike_Smith
Mike_Smith

Reputation: 31

Property 'length' does not exist on type 'HTMLElement'

I am trying to loop over the number of nav-items i have. But when i am doing this, i get the error: Property 'length' does not exist on type 'HTMLElement'. I know i can change document.getElementById('nav-item) to document.getElementsByClassName('nav-item') and the error goes away. But i am not trying to do that. I was access the element through its id. Can anyone please help me with this?

const header = document.getElementById('applicationLinks');
const navItems = document.getElementById('nav-item');
for (let i = 0; i < navItems.length; i++) {
    navItems[i].addEventListener('click', function () {
      const current = document.getElementsByClassName('active');
      current[0].className = current[0].className.replace('active', '');
      this.className += ' active';
    });
}

Thank you, I am a newbie so any help would be appreciated.

Upvotes: 1

Views: 4655

Answers (1)

Train
Train

Reputation: 3506

Your problem is the for loop.

the code

const navItems = document.getElementById('nav-item');

Does not return an array of elements. It returns a single object.

So remove the for loops.

Try this

const header = document.getElementById('applicationLinks');
const navItems = document.getElementById('nav-item');

navItems.addEventListener('click', function () {
      const current = document.getElementsByClassName('active');
      current[0].className = current[0].className.replace('active', '');
      this.className += ' active';
    });
}

if navItems were changed to document.getElementsByClassName('nav-item'); Then you would get your array of objects. That would make the for loop work.

Upvotes: 1

Related Questions