选择具有特定背景颜色的元素

时间:2008-11-11 21:31:25

标签: jquery css jquery-selectors

我想在span中选择一堆div,其CSS包含特定的背景颜色。我如何实现这一目标?

3 个答案:

答案 0 :(得分:43)

如果我正确理解了问题,则选择器[attribute=value] 将无效,因为<span>不包含属性“background-color”。你可以快速测试一下,确认它不匹配任何东西:

$('#someDiv span[background-color]').size(); // returns 0

下式给出:

.one, .two {
  background-color: black;
}

.three {
  background-color: red;
}

这是可行的代码

$('div#someDiv span').filter(function() {
    var match = 'rgb(0, 0, 0)'; // match background-color: black
    /*
        true = keep this element in our wrapped set
        false = remove this element from our wrapped set
                                                         */
    return ( $(this).css('background-color') == match );

}).css('background-color', 'green'); // change background color of all black spans
.one, .two {
  background-color: black;
}

.three {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<div id="someDiv">
    <span class="one">test one</span>
    <span class="two">test two</span>
    <span class="three">test three</span>
</div>

答案 1 :(得分:1)

Javascript 方法

  1. 获取所有跨度
  2. 将跨度节点列表转换为数组
  3. 过滤器跨度数组
  4. 更改匹配的跨度元素的背景颜色

// Get all spans
let spans = document.querySelectorAll('div#someDiv span'); 

// Convert spans nodeslist to array
spans = Array.from( spans ); 

// Filter spans array
// Get CSS properties object of selected element - [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle)
let arr = spans.filter( span => String( document.defaultView.getComputedStyle( span, null ).backgroundColor ) == 'rgb(0, 0, 0)' );

// Change background color of matched span elements
arr.forEach( span => {
    span.style.backgroundColor = 'green';
});
.one, .two {
  background-color: black;
}

.three {
  background-color: red;
}
<div id="someDiv">
    <span class="one">test one</span>
    <span class="two">test two</span>
    <span class="three">test three</span>
</div>

答案 2 :(得分:-7)

使用属性选择器[attribute = value]查找某个属性值。

#id_of_the_div span[background-color=rgb(255,255,255)]