使用Java的Div计算多少个UL元素?

问题描述 投票:1回答:3

我正在将UL元素动态添加到DIV元素。我希望能够计算DIV中有多少个UL元素,以便一旦动态删除所有UL,就可以删除其中包含的DIV。

<div id="000">

<ul id="000-1">
<li>Stuff</li>
<li>Stuff</li>
</ul>

<ul id="000-2">
<li>Stuff</li>
<li>Stuff</li>
</ul>

</div>

是否有一个简单的Javascript解决方案可以计算UL的数量,以便我可以执行类似的操作。?

if(ulcount == 0){

var remove = document.getElementById("000");
remove.innerHTML = '';
results.parentNode.removeChild("000");

}

谢谢。

javascript html count html-lists removechild
3个回答
4
投票

@@ Cheeso的答案是一个很好的纯JS解决方案。但是,如果您使用的是jQuery,则可以简化该过程。

jQuery('div#000').children('ul').length;

上面的代码将返回ul的子div#000元素的数量。

要在动态添加元素时更新计数,您将必须创建一个函数并在发生更改时调用它以更新数字:

function countUls() {jQuery('div#000').children('ul').length;}

将其绑定到事件,以便在您想要更新号码时将其调用。


2
投票

代码:

    function getDirectChildrenByTagName(elt,tagname) {
        var allChildren = elt.children, wantedChildren=[], i, L;
        tagname = tagname.toUpperCase();
        for(i=0, L=allChildren.length; i<L; i++) {
            if (allChildren[i].tagName.toUpperCase() == tagname) {
                wantedChildren.push(allChildren[i]);
            }
        }
        return wantedChildren;
    }

以这种方式使用:

var zero = document.getElementById("000");  
var uls = getDirectChildrenByTagName(zero, 'UL');
var ulCount = uls.length;
  ....

0
投票

尝试一下:

var x = document.getElementById("000-1").querySelectorAll("li").length
                  console.log(">>>>", x);
© www.soinside.com 2019 - 2024. All rights reserved.