Quick question everyone. I know you can select multiple elements with jQuery and change CSS properties in one line of code, like this:
$("#custom-h1-id-6, #custom-h1-id-5, #custom-h1-id-4, #custom-h1-id-3, #custom-h1-id-2").css({ 'position' : 'absolute', 'opacity' : '0'});
But recently I was listening to the ShopTalk Podcast, during which they mentioned that it's a better idea to assign all of your DOM lookups to variables at the beginning of your Javascript file, and then use that variable throughout your file. This I did, and but when I got to the point where I needed to change the CSS of all those elements, I realized I couldn't think of another way to do so besides writing a single line for each element, like this:
n2.css({ 'position' : 'absolute', 'opacity' : '0'});
n3.css({ 'position' : 'absolute', 'opacity' : '0'});
n4.css({ 'position' : 'absolute', 'opacity' : '0'});
n5.css({ 'position' : 'absolute', 'opacity' : '0'});
n6.css({ 'position' : 'absolute', 'opacity' : '0'});
Is there a more concise way to change the css of all these variable equivalent to the one-line jQuery way? I could make an array and iterate through them I guess, but that almost defeats the performance point of not performing multiple DOM lookups on the same item...
I'm sure there's something simple I forgetting for this, thanks!
Easy Solution:
If you have already multiple variables defined, you can select them all with a jQuery selector function, and then just perform the CSS on that one selector:
$([ n2, n3, n4, n5, n6 ]).each(function() {
$(this).css({ 'position' : 'absolute', 'opacity' : '0'});
});
Update: Edited above exaple to work. Must iterate over this with an each()
function.
Alternative Solution:
If you have to a similar operation multiple times, either:
What they meant was probably this, you use variable example
to store the query, and then use it where you need it so the code would be like this :
var example = $("#custom-h1-id-6, #custom-h1-id-5, #custom-h1-id-4, #custom-h1-id-3, #custom-h1-id-2")
// when you need to change props of elements selected by query in example you use :
example.css({ 'position' : 'absolute', 'opacity' : '0'});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With