Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
114 views
in Technique[技术] by (71.8m points)

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...