Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
124
rated 0 times [  128] [ 4]  / answers: 1 / hits: 17817  / 12 Years ago, mon, april 30, 2012, 12:00:00

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


More From » selector

 Answers
38
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)
}
}
}

[#85885] Saturday, April 28, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nestorjarettg

Total Points: 451
Total Questions: 108
Total Answers: 108

Location: Rwanda
Member since Thu, Feb 10, 2022
2 Years ago
;