How to take the links of a Nav with Javascript and add a class?

Asked

Viewed 85 times

2

I got the following nav:

<nav>
  <ul>
     <li><a href="">1</a></li>
     <li><a href="">2</a></li>
     <li><a href="">3</a></li>
  </ul>
</nav>

and the Javascript code:

var linkElement = document.querySelector('nav a');

linkElement.classList.add('blue');

But in doing so it adds the class only in the first element.

If I do so:

var linkElement = document.querySelectorAll('li a');

or

var linkElement = document.getElementsByTagName('a');

It returns me the following error:

Uncaught Typeerror: Cannot read Property 'add' of Undefined

How do I add the class to all links ?

1 answer

2


On your first attempt you only managed to change from the first element of the list because the querySelector gets only the first found element of the document.

To get all the elements you must use the function querySelectorAll. What this function does is to return an Array containing all the elements found. An error was thrown in the second attempt where you call this function, precisely because you tried to use the attribute classList that does not exist in arrays.

In the third attempt, the error was also released for the same reason since the function getElementsByTagName returns an Array containing all elements with a tag that you specified.

In order for the code to work, you must traverse the elements obtained from the Array through a loop for, thus:

var linkElement = document.querySelectorAll('nav a');

for (element of linkElement){
    element.classList.add('blue');
}
<nav>
  <ul>
     <li><a href="">1</a></li>
     <li><a href="">2</a></li>
     <li><a href="">3</a></li>
  </ul>
</nav>

  • Got it, this returning Array is Nodelist? I read in the documentation, but as I’m starting out, I couldn’t quite understand that part. Even, problem solved.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.