Javascript:每三个子节点循环一次
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4274673/
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
Javascript: Loop Through every third child node
提问by Florian Müller
If I got a parent node, how can I loop through every third child node?
如果我有一个父节点,我如何遍历每三个子节点?
I've got now this code:
我现在有这个代码:
var parents = document.getElementById('ID_of_parent');
var first_child = parents.firstChild.data.id;
alert(parents);
alert(first_child);
For the parents, i got now '[object HTMLDivElement]' and for first_child i got 'undefined'.
对于父母,我现在得到了“ [object HTMLDivElement]”,而对于 first_child,我得到了“ undefined”。
回答by Gabi Purcaru
var nodes = document.getElementById('ID_of_parent').childNodes;
for(i=0; i<nodes.length; i+=3) {
alert(nodes[i]);
}
回答by Tomas Jansson
Have you consider jQuery?
你考虑过jQuery吗?
$("#ID_of_parent > *:nth-child(3n)").each(function() { alert(this);});
I implemented a demo here: http://jsbin.com/ahije4/5
我在这里实现了一个演示:http: //jsbin.com/ahije4/5
回答by Ioannis Karadimas
The element.childNodes
collection is what you need.
You need to skip the child nodes that are not elements (element.nodeType != 1
).
该element.childNodes
集合是你所需要的。您需要跳过不是元素 ( element.nodeType != 1
)的子节点。
var d = document.getElementById("ID_of_parent");
if (d)
{
for(var i = 0; i < d.childNodes.length; i++)
{
if (d.childNodes[i].nodeType == 1)
alert(typeof(d.childNodes[i]) + "- " + d.childNodes[i].nodeType + ": " + d.childNodes[i].tagName + " - " + d.childNodes[i].innerHTML);
}
}
回答by rektide
function makeSkippingIterator(parent,stride) {
if(isNaN(stride) || stride < 1)
stride = 1
var node = parent.firstChild
return function() {
var returnable = node,
cnt = stride
while(--cnt >= 0 && node) {
node = node.nextElementSibling
}
return returnable
}
}
keep calling the generator you get back until it has no value for you.
继续调用您返回的生成器,直到它对您没有价值为止。
回答by Chetabahana
I would recommend to use .css()
and or each
with jQuery
//set node attribute
($('#ID_of_parent > third_child').css( 'propertyName' , 'value' );
//execute each nodes
$.each($('#ID_of_parent'), function( key, child ) {
console.log(child);
});
You may see a working sample here:
https://jsfiddle.net/chetabahana/8x65wq32/20/
你可以在这里看到一个工作示例:https:
//jsfiddle.net/chetabahana/8x65wq32/20/