I am trying to do the following:
a) Add a class from an array containing the values one, two, three to all the divs with the class .tab-col. The first div in the class .tab-col should have the class one, second div should have class two, etc. => This is what addCol() does in code below
b) After a) is done, trying to grab the tab-col divs, and adding the class one to the first child element (col-attr), two to the second, etc. . => What addAttr() is attempting to do.
I have succeeded with a) and partially succeeded with b). The problem I am having is that only the .tab-col one's children elements are being labelled with the classes one, two, three. Whereas the other tab-cols children are not adding the classes one, two and three to their children elements.
function addCol() {
var elements = document.querySelectorAll(".tab-col");
var array = ["one", "two", "three", "four", "five", "six", "seven", "eight"];
var index = 0,
length = elements.length;
for (; index < length; index++) {
elements[index].classList.add(array[index]);
}
}
addCol();
function addAttr() {
var elements = document.querySelectorAll(".tab-col");
var array = ["one", "two", "three", "four", "five", "six", "seven", "eight"];
var index = 0,
length = elements.length;
for (; index < length; index++) {
var select = document.querySelectorAll(".tab-col" + "." + array[index] + "> .col-attr");
for (var i = 0, length = select.length; index < length; i++) {
select[i].classList.add(array[i]);
}
}
}
addAttr();
<div class="table">
<div class="tab-col">
<div class="col-attr"></div>
<div class="col-attr"></div>
<div class="col-attr"></div>
</div>
<div class="tab-col">
<div class="col-attr"></div>
<div class="col-attr"></div>
<div class="col-attr"></div>
</div>
<div class="tab-col">
<div class="col-attr"></div>
<div class="col-attr"></div>
<div class="col-attr"></div>
</div>
</div>
Here is a JSBIN replicating the problem: http://jsbin.com/hohuxewixi/edit?html,css,js,output
(Note: Because there is no content, you will have to open up your browser's console in the output area (inspect element))
My question how can I have .tab-col two and .tab-col three to have their children elements (.col-attr) have the classes one, two and three, just as it is for .tab-col one (if you look at the completed JSBIN that will run the JavaScript)?
Any help would be greatly appreciated!
classList?lengthin the innerforloop.classList.