使用 Javascript 将类添加到每个第三个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10385140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:41:15  来源:igfitidea点击:

Add Class to every 3rd Element with Javascript

javascriptselectornodes

提问by Marian

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 thisthread 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:

我正在尝试使用 javascript 选择父元素的每三个元素并向其添加一个 css 类。对我来说听起来很简单,但我无法让它工作。我发现这个线程对我来说看起来很不错,可以完成它,但我对 javascript 非常感兴趣,我的尝试没有成功:

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

当我加载它时,什么也没有发生。
任何修复,大开眼界和提示表示赞赏。
问候,玛丽安

回答by Raynos

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")
        }
    }
}

回答by contactmatt

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

我发现确定每三分之一的最直接的方法是在做模数时给索引加 1:

var nodes = //get nodes

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

  if (isThirdIteration) {
    this.className += ' newClassName';
  }
}?

回答by Andris

You can do it with pure CSS. Javascript isn't needed ;)

您可以使用纯 CSS 来实现。不需要 Javascript ;)

Example: .parent .child:nth-of-type(3n+3)

例子: .parent .child:nth-of-type(3n+3)

回答by Jonathan Payne

This returns a list of elements:

这将返回一个元素列表:

document.getElementsByClassName("ParentsClassName")

You can either iterate over the list, or select an index:

您可以遍历列表,或选择一个索引:

document.getElementsByClassName("ParentsClassName")[0].childNodes;