Select an element with a background color that does not work in jQuery

Please check my code. The background color check condition does not work.

https://jsfiddle.net/oL7tdL22/1/

$(function(){ $(".testing").each(function(){ if($(this).css("background-color")=="rgb(255,193,0)"){ alert("found"); } else{ alert("not found"); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <div class="parent"> <div class="testing" style="background-color:rgb(255,193,0)"> Test </div> </div> <div class="parent"> <div class="testing" style="background-color:rgb(220, 4, 81)"> Test </div> </div> <div class="parent"> <div class="testing" style="background-color:rgb(0, 186, 76)"> Test </div> </div> 

When we warn the background color, it works. But we can not match the colors.

+5
source share
2 answers

you need to specify a space after each comma in the rgb color code, for example rgb(255, 193, 0) . Then it works.

 $(function(){ $(".testing").each(function(){ if($(this).css("background-color")=="rgb(255, 193, 0)"){ alert("found"); } else{ alert("not found"); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <div class="parent"> <div class="testing" style="background-color:rgb(255,193,0)"> Test </div> </div> <div class="parent"> <div class="testing" style="background-color:rgb(220, 4, 81)"> Test </div> </div> <div class="parent"> <div class="testing" style="background-color:rgb(0, 186, 76)"> Test </div> </div> 
+5
source

You need to separate the rgb values ​​with a space, since jQuery thus parses the value of .css("background-color") .

 rgb(X, Y, Z) β–² β–² 

This is the correct code:

 if($(this).css("background-color")=="rgb(255, 193, 0)"){ alert("found"); } 

Code snippet:

 $(function(){ $(".testing").each(function(){ if($(this).css("background-color")=="rgb(255, 193, 0)") alert("found"); else alert("not found"); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <div class="parent"> <div class="testing" style="background-color:rgb(255,193,0)">Test</div> </div> <div class="parent"> <div class="testing" style="background-color:rgb(220, 4, 81)">Test</div> </div> <div class="parent"> <div class="testing" style="background-color:rgb(0, 186, 76)">Test</div> </div> 
+3
source

Source: https://habr.com/ru/post/1269554/


All Articles