"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Select Spans with a Specific Background Color in jQuery?

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

Published on 2024-11-17
Browse:804

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');
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3