【问题标题】:Use JavaScript to find element by its CSS property value使用 JavaScript 通过其 CSS 属性值查找元素
【发布时间】:2022-07-08 16:15:07
【问题描述】:

如何通过匹配其 CSS 属性值找到该元素?

例如,如果元素的背景颜色是绿色,那么做点什么……

const elm = document.getElementsByClassName('elm');

[...elm].forEach(function(s) {
  //find the element which background color is green
  
  //then console.log(theItem)
})
.elm {
  width: 200px;
  height: 100px;
}

.elm1 {
  background-color: red;
}

.elm2 {
  background-color: green;
}

.elm3 {
  background-color: blue;
}
<div class="elm elm1"></div>
<div class="elm elm2"></div>
<div class="elm elm3"></div>

【问题讨论】:

  • getComputedStyle 可以提供帮助,但在此特定示例中,您可以只使用 .getElementsByClassName('elm2')
  • @NickParsons 谢谢,我看到了文档,他将getComputedStyle 用于一个元素,我想不出如何使用它来检查具有相同类名的多个项目......
  • 在您的代码中,您已经有一个循环遍历您的所有元素,因此s 是一个您可以检查其样式的单个元素,然后如果它推入一个数组有你想要的颜色。

标签: javascript html css


【解决方案1】:

您可以对每个元素使用window.getComputedStyle() 方法来检查元素是否具有您的绿色背景颜色。对于green 颜色,计算出来的样式是rgb(0, 128, 0) 的RGB 颜色。通过使用.filter(),您可以返回一个新的元素数组,这些元素具有该值的计算背景颜色:

const elm = document.getElementsByClassName('elm');

const greenElms = [...elm].filter(function(s) {
  const bgColor = getComputedStyle(s).backgroundColor;
  return bgColor === "rgb(0, 128, 0)";
});
console.log(greenElms);
.elm {
  width: 200px;
  height: 100px;
}

.elm1 {
  background-color: red;
}

.elm2 {
  background-color: green;
}

.elm3 {
  background-color: blue;
}
<div class="elm elm1"></div>
<div class="elm elm2"></div>
<div class="elm elm3"></div>

但是,大多数情况下,您的 CSS 是静态的,因此您在编写 JS 代码时会知道负责设置元素样式的样式/选择器是什么,因此您可以改用 .querySelectorAll()匹配绿色背景样式所应用的相同元素,例如:

const greenElms = document.querySelectorAll('.elm2'); // NodeList (similar to an array)
console.log(greenElms);
.elm {
  width: 200px;
  height: 100px;
}

.elm1 {
  background-color: red;
}

.elm2 {
  background-color: green;
}

.elm3 {
  background-color: blue;
}
<div class="elm elm1"></div>
<div class="elm elm2"></div>
<div class="elm elm3"></div>

【讨论】:

  • 您好,第一个解决方案很好,但是否可以将 greenElms 设为元素而不是对象?过滤器函数返回一个对象,我使用getElementsByClassName的原因是我需要它是一个元素。
  • @nakar20966 过滤器函数返回一个元素数组。如果你有多个绿色元素,你想要什么结果?你只想要第一个吗?
  • getElementsByClassName 返回元素的 HTMLCollection(类似于数组)。它不返回单个元素。
  • 如果只需要一个元素,可以将.filter()改为.find()
  • 我只需要第一个元素,因为我确信只有一个元素匹配条件。我刚刚尝试将filter 更改为find 方法,现在它运行良好!非常感谢
【解决方案2】:

根据 Nick Parsons 的回答,我想出了一种在任何元素中搜索任何属性的方法:

const searchByProperty = (property) =>
    Array.from(document.querySelectorAll('*')).filter((s) => {
        const value = getComputedStyle(s)[property];
        console.log(property, value);
    });

用法:

searchByProperty('backgroundColor');

【讨论】:

    猜你喜欢
    • 2012-07-08
    • 2020-10-30
    • 2012-06-30
    • 2014-03-12
    • 2020-05-02
    • 2015-11-27
    • 2020-01-01
    • 1970-01-01
    相关资源
    最近更新 更多