What's wrong with this Javascript code?

3

I wanted to add the class tab-active to all the span tag of the menuMobileTabs div. What's wrong?

<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>
    
asked by anonymous 30.11.2016 / 13:39

4 answers

6

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

    
30.11.2016 / 13:50
4

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

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

The correct one would be:

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

Additionally, querySelector can bring an element, use querySelectorAll

    
30.11.2016 / 13:50
3

You must use querySelectorAll instead of querySelector the difference is that it takes all occurrences, 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 briefly:

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

30.11.2016 / 13:51
1

The error is in querySelector , you have to use querySelectorAll , so it takes all occurrences.

    
30.11.2016 / 14:00