Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Class to every 3rd Element with Javascript

I'm trying to select every third element of a parent with javascript and add a css class to it. Sounds pretty simple to me but I can't get it work. I found this thread which looked quite nice to me to get that done, but I'm such a wuss with javascript that my tries didn't work out:

var nodes = document.getElementsByClassName("ParentsClassName").childNodes;
for(i=0; i<nodes.length; i+=3) {
  this.className += ' newClassName';
}​

When I load this, nothing happens at all.
Any fixes, eyeopeners and tips appreciated.
Greetings, Marian

like image 660
Marian Avatar asked Dec 04 '22 04:12

Marian


2 Answers

var parents = document.getElementsByClassName("someClass"),
    forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach),
    filter = Array.prototype.filter.call.bind(Array.prototype.filter)

forEach(parents, addClassToEveryThirdChild)

function addClassToEveryThirdChild(parent) {
    filter(parent.children, selectEveryThirdChild)
        .forEach(addSomeClass)
}

function selectEveryThirdChild(elem, i) {
    return i % 3 === 0
}

function addSomeClass(elem) {
    elem.classList.add("newClassName")
}

Or with loops

var parents = document.getElementsByClassName("someClass")

for (var i = 0, ii = parents.length; i < ii; i++) {
    var parent = parents[i],
        children = parent.children

    for (var j = 0, jj = children.length; j < jj; j++) {
        var elem = children[j]
        if (j % 3 === 0) {
            elem.classList.add("newClassName")
        }
    }
}
like image 117
Raynos Avatar answered Dec 20 '22 07:12

Raynos


I found that the most straight-forward approach to determining every third, is to add 1 to index when doing the modulus:

var nodes = //get nodes

for(var i = 0; i < nodes.length; i++) {
  var isThirdIteration = (i + 1) % 3 === 0;

  if (isThirdIteration) {
    this.className += ' newClassName';
  }
}​
like image 38
contactmatt Avatar answered Dec 20 '22 08:12

contactmatt