简体   繁体   中英

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. But I don't have to use JQuery I need to do it in pure 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

and

the elements are styled from an external css file

This means you'll have to individually check each element with getComputedStyle (or on obsolete versions of IE, currentStyle ).

You said you have a list, so if I assume you have a NodeList or HTMLCollection , we can use 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 :

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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