Javascript 计算一个div中有多少个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12237529/
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-08-23 07:28:30  来源:igfitidea点击:

Count how many elements in a div

javascripthtml

提问by

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.

我有一个里面有 span 的 div。有没有办法计算 div 中的元素数量,然后将其作为值给出。例如,一个 div 中有 5 个跨度,然后它会计算它并警告 5。请在 Javascript 中。

Thank you.

谢谢你。

采纳答案by Scott

You can use this function, it will avoid counting TextNodes. You can choose to count the children of the children (i.e. recursive)

您可以使用此功能,它将避免计算 TextNodes。您可以选择计算孩子的孩子(即递归)

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

在这里尝试: JS Fiddle

回答by Oriol

If you want the number of descendants, you can use

如果你想要后代的数量,你可以使用

var element = document.getElementById("theElementId");
var numberOfChildren = element.getElementsByTagName('*').length

But if you want the number of immediate children, use

但是如果你想要直接孩子的数量,使用

element.childElementCount

See browser support here: http://help.dottoro.com/ljsfamht.php

在此处查看浏览器支持:http: //help.dottoro.com/ljsfamht.php

or

或者

element.children.length

See browser support here: https://developer.mozilla.org/en-US/docs/DOM/Element.children#Browser_compatibility

在此处查看浏览器支持:https: //developer.mozilla.org/en-US/docs/DOM/Element.children#Browser_compatibility

回答by Chango

Without jQuery:

没有 jQuery:

var element = document.getElementById("theElementId");
var numberOfChildren = element.children.length

With jQuery:

使用 jQuery:

var $element = $(cssSelectocr);
var numberOfChildren = $element.children().length;

Both of this return only immediate children.

这两者都只返回直接的孩子。

回答by Sandeep G B

With jQuery; checks only for spans inside a div:

使用 jQuery;仅检查 div 内的跨度:

JSFiddle

JSFiddle

$(function(){
    var numberOfSpans = $('#myDiv').children('span').length;
    alert(numberOfSpans);
})();?

回答by jfriend00

To count all descendant elements including nested elements in plain javascript, there are several options:

要计算纯 javascript 中包括嵌套元素在内的所有后代元素,有几个选项:

The simplest is probably this:

最简单的大概是这样:

var count = parentElement.getElementsByTagName("*").length;

If you wanted the freedom to add more logic around what you count, you can recurse through the local tree like this:

如果您想要自由地围绕您的计数添加更多逻辑,您可以像这样递归本地树:

function countDescendantElements(parent) {
    var node = parent.firstChild, cnt = 0;
    while (node) {
        if (node.nodeType === 1) {
            cnt++;
            cnt += countDescendantElements(node);
        }
        node = node.nextSibling;
    }
    return(cnt);
}

Working Demo: http://jsfiddle.net/jfriend00/kD73F/

工作演示:http: //jsfiddle.net/jfriend00/kD73F/

If you just wanted to count direct children (not deeper levels) and only wanted to count element nodes (not text or comment nodes) and wanted wide browser support, you could do this:

如果您只想计算直接子节点(而不是更深层次)并且只想计算元素节点(不是文本或评论节点)并且想要广泛的浏览器支持,您可以这样做:

function countChildElements(parent) {
    var children = parent.childNodes, cnt = 0;
    for (var i = 0, len = children.length; i < len; i++) {
        if (children[i].nodeType === 1) {
            ++cnt;
        }
    }
    return(cnt);
}

回答by Krycke

With jQuery you can do like this:

使用 jQuery,您可以这样做:

var count = $('div').children().length;
alert( count );???

Here's a Fiddle: http://jsfiddle.net/dryYq/1/

这是一个小提琴:http: //jsfiddle.net/dryYq/1/

回答by Safwat Fathi

i might add just stupid and easy one answer

我可能会添加一个愚蠢而简单的答案

<div>this is div no. 1</div>
<div>this is div no. 2</div>
<div>this is div no. 3</div>

you can get how many divs in your doc with:

您可以通过以下方式获取文档中的 div 数量:

const divs = document.querySelectorAll('div');
console.log(divs.length) // 3