简体   繁体   English

如何使用JavaScript通过CSS属性值选择元素

[英]How to select elements by CSS property value using JavaScript

I need to get the count of all elements on the page which have display property set to block. 我需要获取页面上具有display属性设置为block的所有元素的计数。 But I don't have to use JQuery I need to do it in pure JavaScript 但是我不必使用JQuery,我需要使用纯JavaScript来实现

In a comment you've said: 在评论中,您说过:

I have a list of items( li elements) on the html and I need to get the count of all li elements which have display property block 我在html上有一个项目列表( li元素),我需要获取所有具有display属性块的li元素的计数

and

the elements are styled from an external css file 元素从外部CSS文件设置样式

This means you'll have to individually check each element with getComputedStyle (or on obsolete versions of IE, currentStyle ). 这意味着您必须使用getComputedStyle (或在IE的过时版本currentStyle )分别检查每个元素。

You said you have a list, so if I assume you have a NodeList or HTMLCollection , we can use Array.prototype.reduce : 您说您有一个列表,所以如果我假设您有一个NodeListHTMLCollection ,我们可以使用Array.prototype.reduce

var count = Array.prototype.reduce.call(yourList, function(count, element) {
    return count + (getComputedStyle(element).display === "block" ? 1 : 0);
}, 0);

If you have to support obsolete versions of IE, you'll want to check for currentStyle : 如果必须支持IE的过时版本,则需要检查currentStyle

var getStyle = window.getComputedStyle || function getStyle(element) {
    return element.currentStyle;
};
var count = Array.prototype.reduce.call(yourList, function(count, element) {
    return count + (getStyle(element).display === "block" ? 1 : 0);
}, 0);

If you need a list of them rather than just the count (you've said "count," but...), use filter instead: 如果您需要它们的列表 ,而不只是计数(您说过“ count”,但是...),请改用filter

var getStyle = window.getComputedStyle || function getStyle(element) {
    return element.currentStyle;
};
var filtered = Array.prototype.filter.call(yourList, function(element) {
    return getStyle(element).display === "block";
});

Please try it: 请尝试:

const elementsWithDisplayBlockProperty = []
document.querySelectorAll("body *").forEach(element => {
    window.getComputedStyle(element).getPropertyValue("display") === "block" && elementsWithDisplayBlockProperty.push(element)
})

console.log(elementsWithDisplayBlockProperty) // result

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM