jQuery Select Elements with a certain CSS
Asked Answered
B

3

10

I'm trying to add a bit of jQuery code to all elements that have position:fixed set on them. Is this sort of thing possible? It would be very helpful if there is, so I don't have to go through all my code and an extra class to the objects that are fixed.

Betatron answered 13/2, 2012 at 3:42 Comment(0)
S
24

This one should cover all cases:

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

Not as fast as qwertymk's answer, but also work if the css property is inherited from another rule, as demonstrated here.

Santanasantayana answered 13/2, 2012 at 4:7 Comment(2)
I just was about to post this same exact code, as I ran into it while messing with his code and did the same thing as you, and it worked. Perfectly, thank you so muchBetatron
@mgibsonbr: A better answer than mine. +1Besnard
B
4

Faster and safer than Colin's answer:

$('*').filter(function(){ return this.style && this.style.position === 'fixed'; });

More about jQuery filter()

Blakeley answered 13/2, 2012 at 3:51 Comment(2)
just curious to know what is returned when this.style and this.style.position==='fixed' are written seperately ?Greenock
@MegaRacer it's a protective check, if this.style is undefined this.style.position will throw an error Cannot read property position of undefined since the compiler checks left to right, if this.style === undefined it will fail the expression before the && not causing an error.Decline
O
1

If you are only checking for display: none and other display properties. You could use the CSS selector :visible in your usual jQuery selections, like this:

$('.items:visible')

Or to select the hidden elements:

$('.items:hidden')
Overelaborate answered 14/10, 2018 at 0:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.