Changing CSS on multiple Javascript variables

Quick question. I know that you can select multiple elements using jQuery and change the CSS properties in one line of code, for example:

        $("#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 lately, I was listening to the ShopTalk podcast, during which they mentioned that it is best to assign all your DOM searches to variables at the beginning of your Javascript file, and then use that variable in your file. I did this, but when I got to the point where I needed to change the CSS of all these elements, I realized that I could not think of another way to do this, except that I wrote one line for each element, for example:

    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 shorter way to change the css of this whole variable equivalent to single-line jQuery? I can make an array and iterate through them, I think, but it almost defeats the performance point without having to do multiple DOM searches on the same element ...

I’m sure that there is something simple forgotten, thanks!

+4
source share
6 answers

A simple solution :

If you already have several variables, you can select them all using the jQuery selector function , and then just execute CSS on that selector:

$([ n2, n3, n4, n5, n6 ]).each(function() {
    $(this).css({ 'position' : 'absolute', 'opacity' : '0'});
});

. , . each().


:

, :

  • jQuery, ( ).
  • , ( ).
+4

, , , , example , , , :

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'});
+1

, DOM- Javascript

, .

. , - . "" jQuery, , , .

jQuery - DOM, CSS, , , . , jQuery .

id, . , , .

+1

, , , . , :

$([ n2, n3, n4, n5, n6 ]).each(function() {
        $(this).css({ 'position' : 'absolute', 'opacity' : '0'});
});
+1

, dom, "". :

$("#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'});

var elements = $("#custom-h1-id-6, #custom-h1-id-5, #custom-h1-id-4, #custom-h1-id-3, #custom-h1-id-2")

:

elements.css({ 'position' : 'absolute', 'opacity' : '0'});

, , , , , . .

0

jQuery - for , . , , , , , - $("#hello") , $(".hello"). , , , , , , , / :

$("#hello1, #hello2, #hello3").addClass("invisible")
0

Source: https://habr.com/ru/post/1648976/


All Articles