4

I need an attribute selector to match the first div element with an z-index and a value of 0. tTis is how i tried to get hands on the element,by using the css attribute selector syntax in jquery:

$("div[z-index='0']").first().doSomeJqueryStuff() ....

In my document there is an explicitly set z-index with a value of 0 on a div element, but the selector returns no result. Thanks for help!

mcloud79
  • 308
  • 4
  • 10
  • possible duplicate of [jQuery: How to select all elements that have a specific CSS property applied](http://stackoverflow.com/questions/1220834/jquery-how-to-select-all-elements-that-have-a-specific-css-property-applied) – MarcinJuraszek Jul 05 '12 at 09:25

6 Answers6

9

You can apply attribute selector to inline style attribute (* means contains):

div[style*="z-index: 0"]
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Slava
  • 3,445
  • 1
  • 20
  • 16
  • Thanks. Really helped. – Iman Jul 17 '20 at 23:23
  • Make this the most voted answer. Pure CSS is the way, JQuery is unnecessary overhead in this case. Thanks Suraj. – Christian Bonato Mar 28 '21 at 00:55
  • 1
    Nice. However, note that this only works if the `z-index: 0` is specified using a `style` attribute. If the `z-index` rule is part of a ruleset, the element won't be selected. – rinogo Apr 08 '21 at 12:25
5

Try

$('div').each(function({ 
    if ($('div').css('z-index') === '0') { // or ... === 0
        ....
    }
}
Igor Konopko
  • 764
  • 2
  • 13
  • 26
2

No that's not possible. You can not select elemets based on css attribute values that way.

You should apply a class or an id to an element with your CSS value and use that instead or iterate over all elements and check for presence of css attribute (rather costly operation).

Blaster
  • 9,414
  • 1
  • 29
  • 25
1

You can check them one by one untile you found the first with z-index = 0 :

$('div').each(function({ 
    // Check doc about .css() function
});
Damien Locque
  • 1,810
  • 2
  • 20
  • 42
1

You use Sizzle CSS Selector Library.

raymarch
  • 158
  • 6
1

z-index is a CSS property and 0 its value.

CSS selectors are made of HTML (and SVG, ...) id, class, elements, attributes, pseudo and their values (and Sizzle, the selector part of jQuery is made the same way). These CSS selectors are for CSS rules where CSS declarations (property: value) are written and will style the HTML document.

FelipeAls
  • 21,711
  • 8
  • 54
  • 74