我有一个列表项列表,默认情况下显示为:none。我以编程方式将其中的一定数量更改为列表项。
我一直在尝试使用querySelectorAll但是当我尝试时:
document.querySelectorAll("#ulname style[display*='list-item']")
它返回一个空数组(我知道它至少有一个)。
关于如何修改我的选择器或其他方法的想法?我想知道显示了多少项目。
答案 0 :(得分:7)
var liList = document.getElementById("myul").getElementsByTagName("li");
var largo = liList.length
alert(largo);
WHERE“ myul ”是列表的ID, largo 是li项目的数量
<ul id="myul">
<li>hello</li>
<li>world</li>
</ul>
警报将是2
<ul id="myul">
<li>hello</li>
<li>world
<ul>
<li>here we are</li>
<ul>
</li>
</ul>
警报将是3
答案 1 :(得分:-1)
var ul = document.getElementById("myul");
var liNodes = [];
for (var i = 0; i < ul.childNodes.length; i++) {
if (ul.childNodes[i].nodeName == "LI") {
liNodes.push(ul.childNodes[i]);
}
}
totalLis = liNodes.length;
在ul标签中添加文字
var txt = document.createTextNode("gsdgds");
ul.appendChild(txt);
将li标签添加到ul标签
var txt = "<li>dsgdsgs</li>";
ul.innerHTML(txt);
答案 2 :(得分:-1)
<!DOCTYPE html>
<html>
<body onload="myFunction()">
<p>Maybe this answer can help. I improvise for this after a few days of testing. This is what I got. Hope it helps you.</p>
<li class="sidenav-item open active">
<a href="#" class="sidenav-link sidenav-toggle" ></i>
<div class="text-white">Hi, There!
<div class="badge badge-primary" id="ul-me"></div></div>
</a>
<ul class="sidenav-menu" id="ul1">
<li class="sidenav-item active">
<a href="#" class="sidenav-link" >
<div class="text-white" >Home</div>
</a>
</li>
<li class="sidenav-item" id="ul2">
<a href="#" class="sidenav-link" >
<div class="text-white" >Blog</div>
</a>
</li>
<li class="sidenav-item" id="ul3">
<a href="#" class="sidenav-link" >
<div class="text-white" >Downloads</div>
</a>
</li>
<li class="sidenav-item" id="ul4">
<a href="#" class="sidenav-link" >
<div class="text-white" >Contact</div>
</a>
</li>
<li class="sidenav-item" id="ul5">
<a href="#" class="sidenav-link" >
<div class="text-white" >About</div>
</a>
</li>
</ul>
</li>
'''
<!-- Count Item (li) in <ul> -->
<script>
function myFunction() {
var mylist = [document.getElementById("ul1"), ("ul2"), ("ul3"), ("ul4"), ("ul5")];
document.getElementById("ul-me").innerHTML = mylist.length;
}
</script>
</body>
</html>