views:

98

answers:

5

Is there a way to select all elements that have a given style using JavaScript?

Eg, I want all absolutely positioned elements on a page.


I would assume it is easier to find elements by style where the style is explicitly declared:

  • the style is non-inherited (such as positioning)
  • the style is not the default (as would be position:static).

Am I limited to those rules? Is there a better method for when those rules apply?

I would happily to use a selector engine if this is provided by one (ideally Slick - Mootools 1.3)

EDIT:
I came up with a solution that will only work with above rules.
It works by cycling through every style rule, and then selector on page.
Could anyone tell me if this is better that cycling through all elements (as recommended in all solutions).
I am aware that in IE I must change the style to lowercase, but that I could parse all styles at once using cssText. Left that out for simplicity.
Looking for best practice.

var classes = '';
Array.each(documents.stylesheets, function(sheet){
   Array.each(sheet.rules || sheet.cssRules, function(rule){
      if (rule.style.position == 'fixed') classes += rule.selectorText + ',';
   });
});
var styleEls = $$(classes).combine($$('[style*=fixed]'));
A: 

There is no selector for CSS attributes, so you're pretty much stuck to looping through each element and checking it's position.

$("*").each(function() {
    var pos = $(this).css('position');
    if(pos == "absolute") {
        // do something
    }
    else if (pos == "relative") {
        // do something else
    }
});

You can use Case statements instead of if/else as well.

Other than this solution, there is no selector per se that can search by CSS attributes (unless they were inline, maybe).

Marko
I have no issue with JQuery, but you ought to specify that you are using it - I went searching to find out what that .css() function was.
SamGoody
+6  A: 
Gaby
+1  A: 

You can keep Mootools, or whatever you use... :)

function getStyle(el, prop) {
  var view = document.defaultView;
  if (view && view.getComputedStyle) {
    return view.getComputedStyle(el, null)[prop];
  }
  return el.currentStyle[prop];
}

​function getElementByStyle(style, value, tag)​ {
  var all = document.getElementsByTagName(tag || "*");
  var len = all.length;
  var result = [];
  for ( var i = 0; i < len; i++ ) {
    if ( getStyle(all[i], style) === value )
      result.push(all[i]);
  }
  return result;
}
galambalazs
+5  A: 

For Mootools:

var styleEls = $$('*').filter(function(item) {
    return item.getStyle('position') == 'absolute';
});
Scott
+1: It [works](http://jsfiddle.net/nrqhS/), is elegant and is actually in mootools - the preferred library of the asker.
Simen Echholt
A: 

JQuery has some good selectors, and you can see how they work if you want to explore the .js file.

This sample might help: http://api.jquery.com/attribute-contains-selector/

dave