Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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]'));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
111 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...