如何使用属性 display:none 测量类的长度

How to measure the length of a class with the property display:none

本文关键字:测量 none 何使用 属性 display      更新时间:2023-09-26

有没有办法用javaScript jQuery中具有display:none的某个类来测量元素?

例如:

<div class="x" style="display: none;"></div>
<div class="x" style="display: none;"></div>
<div class="x"></div>

如果我在下面执行此代码,我将收到警报"3",因为有 3 个元素带有 class="x"。

var n = document.getElementsByClassName('x').length;
alert(n);

正确的选择器是什么,以便我的警报显示只有 2 个类"x"并显示:无?

感谢您的帮助!

尝试混合类名和 :hidden 选择器。

  var list =  $('.x:hidden'); //select all elements with class x and are hidden.

演示

在香草JS中:

var n = document.getElementsByClassName('x'); //get the elements with class
var nodeList = []; 
for(var i=0, len = n.length; i<len; i++){ //loop through them
    if(n[i].style.display === "none") nodeList.push(n[i]); //check for display property value and push the element to the list.
}
alert(nodeList.length); //You have the list of elements with desired properties.

小提琴