Skip to content
Advertisement

Select Element By CSS style (all with given style)

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]'));

Advertisement

Answer

For Mootools:

var styleEls = $$('*').filter(function(item) {
    return item.getStyle('position') == 'absolute';
});
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement