1

While reading jQuery and Bootstrap documentation I often see this:

var modal = $('#someid');
modal.find('.something').text('something');
modal.find('.somethingelse').text('somethingelse');

It first assigns the element to a variable, then works from there. However I usually write this:

$('#someid').find('.something').text('something');
$('#someid').find('.somethingelse').text('somethingelse');

My question is, are there reasons for using the first method - assigning to a variable - other than the syntax itself? Is it faster or better regarding the DOM?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Kim Steinhaug
  • 478
  • 3
  • 13
  • @Maidul not really a dupe – Rory McCrossan Apr 15 '20 at 14:43
  • So storing it in a variable you look up the element once. Not using it, you look up the element twice. What do you think is more efficient. Using something you have already a reference to or having to search the DOM all over again to find the element? – epascarello Apr 15 '20 at 14:46

1 Answers1

1

The first method is preferred for multiple reasons.

  • It cuts down on the number of times the DOM has to be accessed, which is a relatively slow operation and so it performs better.
  • It reduces the number of times your code instantiates a new jQuery object from an existing Element object, which is another performance benefit.
  • It DRYs up the code so that the same statements are not needlessly repeated.

As such you should always follow this practice, known colloquially as 'caching the selector', where possible.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339