Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select elements by CSS property in JavaScript

Is it possible to select DOM elements by their CSS property?

For example:

awsome_function ({'background-color' : '#0cf'});
// return all object, which's background-color css attribute value is '#0cf'

awsome_function (['background-color']);
// return all object, which has background-color css attribute 

awsome_function (['-my-special-cssattribute'])
// return all object, which has '-my-special-cssattribute' css attribute 

I know that it is possible to select elements using the jQuery each method, like this:

$('*').each(function(){
   if($(this).css('-my-special-cssattribute')) {
      /* do something */
   }
})

However it's maybe slow and unelegant. Is there a cooler way to do that?

like image 844
Nagy Márton Avatar asked Apr 21 '26 01:04

Nagy Márton


1 Answers

I would use a custom selector:

$.extend($.expr[":"], {
    foo: function (e) {
        return $(e).css('background-color') == '#0cf';
    }
});

Usage:

alert($('div:foo').size()); //get the count of all the divs that matches the selector
like image 185
Johan Avatar answered Apr 22 '26 15:04

Johan