简体   繁体   English

在JavaScript中通过CSS属性选择元素

[英]Select elements by CSS property in JavaScript

Is it possible to select DOM elements by their CSS property? 是否可以通过CSS属性选择DOM元素?

For example: 例如:

awsome_function ({'background-color' : '#0cf'});
// return all object, which's background-color css attribute value is '#0cf'

awsome_function (['background-color']);
// return all object, which has background-color css attribute 

awsome_function (['-my-special-cssattribute'])
// return all object, which has '-my-special-cssattribute' css attribute 

I know that it is possible to select elements using the jQuery each method, like this: 我知道可以使用jQuery的each方法选择元素,如下所示:

$('*').each(function(){
   if($(this).css('-my-special-cssattribute')) {
      /* do something */
   }
})

However it's maybe slow and unelegant. 然而,它可能是缓慢和不优雅的。 Is there a cooler way to do that? 有没有更酷的方法呢?

I would use a custom selector: 我会使用自定义选择器:

$.extend($.expr[":"], {
    foo: function (e) {
        return $(e).css('background-color') == '#0cf';
    }
});

Usage: 用法:

alert($('div:foo').size()); //get the count of all the divs that matches the selector

However it's maybe slow and unelegant. 然而,它可能是缓慢和不优雅的。 Is there a cooler way to do that? 有没有更酷的方法呢?

It is slow. 这很慢。 It is unelegant. 它不够优雅。 Don't do that. 不要那样做。 Select your elements with an ID or eventually with a class, but never that way. 选择带有ID或最终带有类的元素,但绝不会这样。 Seriously. 认真。

My suggestion is to append different classes with different background-colors. 我的建议是添加不同背景颜色的不同类。 Then you could select those. 然后你可以选择那些。

Or you could try .css() http://api.jquery.com/css/ 或者你可以试试.css() http://api.jquery.com/css/

Answer : There is no way to do that, and for good reasons. 答:没有办法做到这一点,并且有充分的理由。 It'll be very slow, and it is of course worse than unelegant. 这将是非常缓慢的,它当然比不优雅更糟糕。

Personnaly, if i one day see one of my devs do that, i'll kill him and/or ask my boss to replace him immediately. Personnaly,如果我有一天看到我的一个开发者那样做,我会杀了他和/或让我的老板立即替换他。

Use classes or much bettern ids ! 使用类或更多的id! If you can not, the problem comes from your application structure logic. 如果不能,则问题来自您的应用程序结构逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM