Alex Rivera | Logout

jQuery find by inline css attribute

Asked 2009-07-24T20:43:01.863
23

I need to find an element based on a specific css attribute. The css is applied inline and I can not use a class. Is there anyway to achieve this in jQuery?

Edit
Report

3 Answers

4

I think you might be able to write a custom jQuery selector to do this.

For example, if you want to do select by certain style attribute, you can do:

 jQuery.extend(jQuery.expr[':'], {
    styleEquals: function(a, i, m){
        var styles = $(a).attr("style").split(" ")
        var found = false;
        for (var i = 0; i < styles.length; i++) {
            if (styles[i]===m[3]) {
                found = true;
                break;
            }
        }
        return found;
    }
});

Then it can be used in conjuction with any other selector you can select all input elements with certain style like this:

$('input:styleEquals('width=10px')')
answered 2009-07-24T20:55:40.370
4

Yes, I think the fastest and easiest way to achieve the desired results would be to target styles with a property class selector.

Like stated before:

$('div.yourClass[style*="background-color:Blue"]).css('color', 'White');

That way we target all divs with same class that have blue background and tell them all to have white color text. Of course instead of .css we can use anything here, .animate and tell all blues to be animated etc. This helped me a lot with DB relations and people setting up strange things in DB.

I used to be less generic, and target strings with :contains... but then somebody goes to the base, and changes texts and labels, and bye bye code ;)

Hope it helps.

answered 2013-02-05T09:09:21.923
3

Something like:

$('selector').each(function() {
    if($(this).attr('style').indexOf('font-weight') > -1) {
        alert('got my attribute');
    }
});
answered 2009-07-24T20:48:21.383

Your Answer