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.
jQuery Select Elements with a certain CSS
Asked Answered
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.
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 much –
Betatron
@mgibsonbr: A better answer than mine. +1 –
Besnard
Faster and safer than Colin's answer:
$('*').filter(function(){ return this.style && this.style.position === 'fixed'; });
More about jQuery filter()
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 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')
© 2022 - 2024 — McMap. All rights reserved.