最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Select Element By CSS style (all with given style) - Stack Overflow

programmeradmin5浏览0评论

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)bine($$('[style*=fixed]'));

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]'));
Share Improve this question edited Jul 16, 2010 at 9:59 SamGoody asked Jul 15, 2010 at 21:24 SamGoodySamGoody 14.5k10 gold badges82 silver badges93 bronze badges 3
  • 1 @samgoody Your bullet points are confusing. First one makes various assumptions, then second one seems to discard it by saying - "without making said assumptions" :) – Anurag Commented Jul 15, 2010 at 21:36
  • @Anurag. You are absolutely correct. Thanks. Fixed. (I hope. Is that better?) – SamGoody Commented Jul 16, 2010 at 6:43
  • Your approach seems faster, as a css or getStyle call for each element results in a call to the native getComputedStyle which is time-consuming. CSS rules, OTOH, are already parsed beforehand, and it's simply a matter of looping through them. – Anurag Commented Jul 18, 2010 at 18:05
Add a comment  | 

4 Answers 4

Reset to default 10

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

For Mootools:

var styleEls = $$('*').filter(function(item) {
    return item.getStyle('position') == 'absolute';
});

In jQuery you could use

$('*').filter( function(){
  return ($(this).css('position') == 'absolute');
} );

[update]

Or even create a new selector.
got me interested and so here is one (its my 1st, so its not built for efficiency) to find elements by css property..

$.expr[':'].css = function(obj, index, meta, stack){
  var params = meta[3].split(',');

  return ($(obj).css(params[0]) == params[1]);
};

usage: $('optionalSelector:css(property,value)')
will return all elements (of optionalSelector) whose property = value

example: var visibleDivs = $('div:css(visibility,visible)');
will return all divs whose visibility is set to visible (works for the default visibility as well..)

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

$("*").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).

发布评论

评论列表(0)

  1. 暂无评论