What’s wrong with this Javascript code?

Asked

Viewed 94 times

3

I wanted to add the class tab-active to all the tags span of the div menuMobileTabs. What’s wrong with it?

<div id='menuMobileTabs'>
  <span>Sidebar</span>
  <span>RedeSociais</span>
  <span>Menu</span>
  <span>Search</span>
</div>

<script>
var menuTabs = document.querySelector('#menuMobileTabs span'); 

for(var i = 0;i < menuTabs.length;i++){
  menuTabs[i].classList.add('tab-active');
}
</script>
  • Ready. Ta ai! CDATA is because I use blogger.

  • 1

    Greatly improved with the code, makes it much easier for those who will test.

4 answers

6


Use querySelectorAll to search for the list of elements, querySelector will bring only the first span in this case.

4

If menuTabs is an array, you can access it without an index, as you are doing on that line:

menuTabs.classList.add('tab-active');

The right thing would be:

menuTabs[i].classList.add('tab-active');

Moreover, querySelector can bring an element, use querySelectorAll

3

You have to use the querySelectorAll instead of querySelector the difference is that it takes all occurrences and not just one (in the case the first span).

var menuTabs = document.querySelectorAll('#menuMobileTabs span');

for(i = 0; i < menuTabs.length; i++)
{
  menuTabs[i].classList.add("tag-active");
}
.tag-active {
  color:red;
}
<div id="menuMobileTabs">
  <span>Siber</span>
  <span>Rede Sociais</span>
  <span>Menu</span>
  <span>Search</span>
</div>


You can work in summary:

document.querySelectorAll('#menuMobileTabs span').forEach(function(el)
{
   el.classList.add("tag-active");
});
.tag-active {
  color:blue;
}
<div id="menuMobileTabs">
  <span>Siber</span>
  <span>Rede Sociais</span>
  <span>Menu</span>
  <span>Search</span>
</div>

References

1

The mistake is in the querySelector, you have to use the querySelectorAll, so take all occurrences.

Browser other questions tagged

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