Home  >  Article  >  Web Front-end  >  How to Select Spans with a Specific Background Color in jQuery?

How to Select Spans with a Specific Background Color in jQuery?

Barbara Streisand
Barbara StreisandOriginal
2024-11-06 21:59:02492browse

How to Select Spans with a Specific Background Color in jQuery?

Locating Elements with Specific Background Colors

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn