gpt4 book ai didi

javascript - 如何获取具有特定样式属性值的循环中元素的长度

转载 作者:行者123 更新时间:2023-11-30 13:51:31 25 4
gpt4 key购买 nike

如何在纯 javascript 中获取具有内联样式属性不透明度值“1”的循环元素的长度。我只想用内联样式属性值捕获它们,而不是分配任何类名,因为为了将来的目的,我可能想用不同的属性值捕获它们 或不同的样式属性值。是否有机会通过使用类似这样的东西来获取元素 document.querySelectorAll("li[style*='opacity:1']")

<ul id="all" class="select">
<li class="someclass" style="opacity: 1; display:inline-block;">text</li>
<li class="someclass" style="opacity: 0; display:inline-block;">text</li>
<li class="someclass" style="opacity: 1; display:inline-block;">text</li>
<li class="someclass" style="opacity: 0; display:inline-block;">text</li>
<li class="someclass" style="opacity: 0; display:inline-block;">text</li>
<li class="someclass" style="opacity: 1; display:inline-block;">text</li>
<li class="someclass" style="opacity: 0; display:inline-block;">text</li>
<li class="someclass" style="opacity: 0; display:inline-block;">text</li>
<li class="someclass" style="opacity: 1; display:inline-block;">text</li>
<li class="someclass" style="opacity: 1; display:inline-block;">text</li>
<li class="someclass" style="opacity: 1; display:inline-block;">text</li>
<li class="someclass" style="opacity: 0; display:inline-block;">text</li>
<li class="someclass" style="opacity: 1; display:inline-block;">text</li>
</ul>
<script>
var elem = document.querySelectorAll("li");

// var elem = document.querySelectorAll("li[style*='opacity:1']");

for (var i = 0; i < elem.length; i++) {
if(elem[i].style.opacity == 1){
console.log(elem[i].length);
}
}
</script>

最佳答案

也许你想要这样的东西?它并不比您拥有的好多少。

var elem = Array.from(document.querySelectorAll("li")).filter(el => el.style.opacity == 1);

console.log (elem.length);
<ul id="all" class="select">
<li class="someclass" style="opacity: 1; display:inline-block;">text</li>
<li class="someclass" style="opacity: 0; display:inline-block;">text</li>
<li class="someclass" style="opacity: 1; display:inline-block;">text</li>
<li class="someclass" style="opacity: 0; display:inline-block;">text</li>
<li class="someclass" style="opacity: 0; display:inline-block;">text</li>
<li class="someclass" style="opacity: 1; display:inline-block;">text</li>
<li class="someclass" style="opacity: 0; display:inline-block;">text</li>
<li class="someclass" style="opacity: 0; display:inline-block;">text</li>
<li class="someclass" style="opacity: 1; display:inline-block;">text</li>
<li class="someclass" style="opacity: 1; display:inline-block;">text</li>
<li class="someclass" style="opacity: 1; display:inline-block;">text</li>
<li class="someclass" style="opacity: 0; display:inline-block;">text</li>
<li class="someclass" style="opacity: 1; display:inline-block;">text</li>
</ul>

关于javascript - 如何获取具有特定样式属性值的循环中元素的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58148404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com