Trying to comprehend "this" in my javascript code (one works, the other doesn't)

I am trying to learn javascript refactoring some jquery examples in a book in javascript. In the following code, I add a clicker to the tab and activate it when the user clicks on the tab.

var tabs = document.querySelectorAll(".tabs a span"); var content = document.querySelectorAll("main .content li"); for (var tabNumber = 0; tabNumber <= 2; tabNumber++) { tabs[tabNumber].addEventListener("click", function (event) { for (var i = 0; i < tabs.length; i++) { tabs[i].classList.remove("active"); } tabs[tabNumber].classList.add("active"); for (var i = 0; i < content.length; i++) { content[i].innerHTML = ""; } event.preventDefault(); }); } 
Run codeHide result

This returns undefined error at startup. However, I have tried to replace tabs[tabNumber].classList.add("active") ") on this.classList.add("active") , and it worked.

Why the previous code does not work? As far as I can see, they refer to the same thing, and tabs[tabNumber] should work, since at this point it is code tabs[0] .

+6
source share
2 answers

I think the other answers told you why tabs[tabNumber] does not work (because it is based on the evaluation of the for loop, and so is always a greater value tabNumber).

That's why I would recommend using a cycle .forEach . Beware, because it does not work with arrays of DOM nodes created document.querySelectorAll() , but you can use:

 // ES6 Array.from(document.querySelectorAll('...')) // ES5 [].slice.call(document.querySelectorAll('...')) ) // ES6 Array.from(document.querySelectorAll('...')) // ES5 [].slice.call(document.querySelectorAll('...')) 

In any case, I made a simplified working demonstration of your code. Please note that I retain the current active tab in a variable, in order to prevent another cycle for . You can also do:

 document.querySelector('.active').classList.remove('active') 

But I like to reduce the number of DOM testimony.

Good luck for your apprentissage, rewriting the jQuery code in Vanilla JS, it seems a good way, and you could get a much better understanding of JavaScript.

+3
source

If you use this , I think it's better and more polished solution. If you still want to use tabNumber , he probably appreciates 3 in each callback, because it is the number after the last iteration, and you do not have a position tabs[3] .

So you just need to make private variables tabNumber .

+4
source

All Articles