Home > Article > Web Front-end > How to Select Spans with a Specific Background Color in jQuery?
When dealing with a collection of spans within a div, the goal may be to isolate those with a particular background color. While the [attribute=value] selector might seem intuitive, it proves ineffective for extracting elements based on background-color, as spans lack an attribute by that name.
Instead, consider the CSS selector $('div#someDiv span'). This selects all spans within the designated div. To refine the selection, we can use the filter() function:
$('div#someDiv span').filter(function() { var match = 'rgb(0, 0, 0)'; // Match black background-color return ( $(this).css('background-color') == match ); });
This code isolates spans with a black background, allowing for subsequent operations, such as changing their color:
$('div#someDiv span').filter(function() {...}).css('background-color', 'green');
The above is the detailed content of How to Select Spans with a Specific Background Color in jQuery?. For more information, please follow other related articles on the PHP Chinese website!