JQuery - Should I repeat the selector (store in a variable)?

There are several times when I repeat the selector several times. Should I somehow store the jquery object in a variable and then just use it? As a quick example, how about the following ?:

$('a.contactus').css('padding', '10px');
$('a.contactus').css('margin', '4px');
$('a.contactus').css('display', 'block');

Now I know that this is not a very good example, since effectively you can simply link each css function. But suppose there was a conditional statement between each of them or something that prevented you from chaining.

Is it possible to save a jquery object in a variable? And if so, when should I / can I?

+3
source share
3 answers

You can do it

var myvar = $('a.contactus');
myvar.css('padding', '10px').css('margin', '4px').css('display', 'block');

but for readability I do it

var myvar = $('a.contactus');
myvar.css('padding', '10px')
  .css('margin', '4px')
  .css('display', 'block');

, $(someselector), dom. .

+3

( ) - , , , , $(this) , $("[attr=val]") . , .


, .css():

$('a.contactus').css({ padding: '10px', margin: '4px', display: 'block' });
+12

- jquery , ?

Whenever possible you should use performance . You can, for example, rewrite your code as follows:

var $el = $('a.contactus');
$el.css('padding', '10px');
$el.css('margin', '4px');
$el.css('display', 'block');

You can do it even shorter:

$el.css({
  padding: '10px',
  margin:'4px',
  display: 'block'
});

Saving a common / repeating selector in a variable is also useful when writing jquery plugins to store $(this)in a variable.

+4
source

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


All Articles