如何使用jQuery查找具有特定颜色的元素

如何使用jQuery查找具有特定颜色的元素

问题描述:

这是我的HTML代码

<ul id="components">
    <li>Computer</li>
    <li>Mouse</li>
    <li>Keyboard</li>
    <li>Printer</li>
    <li>CPU</li>
</ul>

#components li:first-child{
    color:red;
}
#components li: nth-child(2){
    color:blue;
}
#components li: nth-child(3){
    color:red;
}
#components li: nth-child(4){
    color:red;
}
#components li: nth-child(5){
    color:green;
}

我需要一个jQuery函数,该函数可以找到所有 red 颜色的 li 元素并将背景转换为黄色

What I need is a jQuery function which can find all the li elements in red color and can convert the background to yellow

我的意思是

$("#components").find(li elements in red color).css("backgound","yellow"); 
// find li elements in red color and change the background to yellow

您可以使用 .filter();

 $('ul li').filter(function() {
   return $(this).css('color') == 'rgb(255, 0, 0)';
 }).each(function() {
   $(this).css('background-color', 'yellow');
 })

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<ul id="components">
  <li style="color:red">Computer</li>
  <li style="color:blue">Mouse</li>
  <li style="color:red">Keyboard</li>
  <li style="color:red">Printer</li>
  <li style="color:green">CPU</li>
</ul>