Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change CSS on Multiple Javascript Variables

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!

like image 475
Jake Evans Avatar asked Feb 06 '23 12:02

Jake Evans


2 Answers

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:

  1. Select all of the elements into a single jQuery variable like the other answers say (inflexible solution).
  2. Add a common class to all the variables and then operate on that class (dynamic solution).
like image 117
Jonathan Lam Avatar answered Feb 09 '23 19:02

Jonathan Lam


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'});
like image 25
Marko Mackic Avatar answered Feb 09 '23 19:02

Marko Mackic