我有一个跨度里面的div。有没有一种方法可以计算div中有多少元素,然后将其作为一个值输出。例如,在一个div中有5个跨度,那么它会计数并提醒五个。请在Javascript中。
谢谢。 您可以使用这个功能,它将避免对TextNodes进行计数。 您可以选择计算子女的子女(即递归)。 $ p $ 函数getCount(parent,getChildrensChildren){ var relevantChildren = 0; var children = parent.childNodes.length; for(var i = 0; i< children; i ++){ if(parent.childNodes [i] .nodeType!= 3){ if(getChildrensChildren) relatedChildren + = getCount(parent.childNodes [i],true); relatedChildren ++; } } 返回relatedChildren; }
用法:
var element = document.getElementById(someElement); alert(getCount(element,false)); //只需一级 alert(getCount(element,true)); //获取所有子节点的数量试试这里: 吉他小提琴
I have a div with span inside of it. Is there a way of counting how many elements in a div then give it out as a value. For Example there were 5 span in a div then it would count it and alert five. In Javascript please.
Thank you.
解决方案You can use this function, it will avoid counting TextNodes. You can choose to count the children of the children (i.e. recursive)
function getCount(parent, getChildrensChildren){ var relevantChildren = 0; var children = parent.childNodes.length; for(var i=0; i < children; i++){ if(parent.childNodes[i].nodeType != 3){ if(getChildrensChildren) relevantChildren += getCount(parent.childNodes[i],true); relevantChildren++; } } return relevantChildren; }Usage:
var element = document.getElementById("someElement"); alert(getCount(element, false)); // Simply one level alert(getCount(element, true)); // Get all child node countTry it out here: JS Fiddle
更多推荐
计算div中有多少个元素
发布评论