I have an HTML file which creates a 5*4 grid using td elements. Each td element has it’s css class with bunch of properties.
I’m trying to switch the css classes of my elements on a button click. Example, if i click ‘up’ button the css classes of each row should be swapped with css class of the row below, and first row should go to the last one.
function switchColorUp() {
var allTDs = document.getElementsByTagName("td");
for (var i = 0; i < allTDs.length; i++) {
allTDs[i].classList = allTDs[(i + 4) % 20].classList;
}
}
Codepen link-
https://codepen.io/001Abhishek/pen/NWzrZyg
It works except for the second row’s css is overlapping the first and last row at same time. Hence the first row’s css gets lost( check the codepen link to verify this behaviour)
Can’t seem to figure out how to handle that case. Any help will be appreciated.
I tried saving first row elements in temp var and then swapping them with the last row and running the for loop till the second last row.
2
Answers
Perhaps, I’m not understanding your objective. I don’t understand the use of
(i+4)%20
when swapping rows that are next to each other; plus running the loop through the full array row will overwrite rows before you capture the old value and(i+4)%20
will exceed the size of the array.From the text of your question, this first snippet appears to move the array values as you’d like to move the classes.
Also, since you know your table structure is fixed or contains a repeating pattern, you could make css styles on table or tr elements that use the :nth-child selector, and then change the style on the table or tr element and all the td elements will change without the need for this swapping. There is an MDN example of a styling like this, but you’d need to make a set of them for each possible combination. See the second snippet for an illustration.
The reason why the first row’s css gets lost is due to the for loop overwriting the first 4 values. The last 4 iterations of the for loop (ie. i = 16,17,18,19) would get the css for the overwritten first 4 elements.
The reason why saving the first row elements into a temp var does not work either is because
classList
returns a liveDOMTokenList
as seen from the documentation, which is essentially a reference.My solution involves saving the first 4 elements as values using the
toString()
function:Hope that helps!