簡體   English   中英

如何使用JavaScript通過CSS屬性值選擇元素

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

我需要獲取頁面上具有display屬性設置為block的所有元素的計數。 但是我不必使用JQuery,我需要使用純JavaScript來實現

在評論中,您說過:

我在html上有一個項目列表( li元素),我需要獲取所有具有display屬性塊的li元素的計數

元素從外部CSS文件設置樣式

這意味着您必須使用getComputedStyle (或在IE的過時版本currentStyle )分別檢查每個元素。

您說您有一個列表,所以如果我假設您有一個NodeListHTMLCollection ,我們可以使用Array.prototype.reduce

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

如果必須支持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);

如果您需要它們的列表 ,而不只是計數(您說過“ 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";
});

請嘗試:

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