For my project, I am required to get the collection of all the elements which have the same class. So, I am doing it with getElementsByClassName
.
var tabs = document.getElementsByClassName("tab");
if (tabs) {
for (var i = 0; i < tabs.length; i++) {
var tab = tabs[i];
console.log(tab); // which outputs as 'undefined'..
console.log(i); // which outputs the nos of the total nodes available with class 'tab'
}
}
I have to retrieve all those elements(which has class 'tab') and apply it another class (say 'bat')..
My question is, why it consoles out undefined as above?? and how can I be able to iterate through all the required nodes sequentially. Is there any code available which can do this??
EDIT ::
Forget to add it..
When clicked on any tab which has 'tabs'
class, it always returns the same result..
var tabs = document.getElementsByClassName("tab");
if (tabs) {
for (var i = 0; i < tabs.length; i++) {
var tab = tabs[i];
tab.addEventListener("click", function() {
console.log(tab[i]); // always returns undefined
console.log(tab); // always returns the last element in the list
console.log(i); // always returns the length of that list (in my case its 3)
}, false);
}
}
How can I be able to iterate through all the available elements sequentially.