计算div中有多少个元素

编程入门 行业动态 更新时间:2024-10-27 08:38:15
本文介绍了计算div中有多少个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个跨度里面的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 count

Try it out here: JS Fiddle

更多推荐

计算div中有多少个元素

本文发布于:2023-10-20 13:05:25,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中有   多少个   元素   div

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!