0

I have a click method that is likely to be used several times. In this method, I need to access the id of the button being clicked on more than one occasion. For example:

$('.elemental-selection').click(function () {
   if(currentElement !== $(this).attr('id')) {
      if($(this).attr('id') === 'element-water') {
         ...
      }
      else {
         currentElement = $(this).attr('id');
      }
    }
});

Of course for long if blocks I could use a switch-statement, but what I'm curious about is if the frequent use of $(this) would be better substituted with a variable defined to be $(this) (and whatever method I want from it). From there and onwards, I'd refer to the variable instead of this.

So, what's the better decision? Thank you.

  • Just don't use jQuery and go for `this.id` directly. – Bergi Mar 23 '16 at 17:45
  • @Bergi They're exactly the same. –  Mar 23 '16 at 17:46
  • Of course they are, that's why I recommended it as a replacement. – Bergi Mar 23 '16 at 17:49
  • 1
    @Bergi What's the reasoning? From my angle, it's like someone telling me to use a silver-colored wrench over my bronze-colored wrench. "Why? They're the same tool with insignificant difference." Person responds, "Exactly". So, I'm confused as to your point. –  Mar 23 '16 at 17:50
  • jQuery is more like the fancily coloured plastic wrench that costs twice as much because of the glitter, and I'm telling you that your standard cheap steel wrench is a much better tool for the job. There's no reason to use jQuery when you don't need it, it's fluff. Makes your code harder to read and slower to execute, with the same outcome. – Bergi Mar 23 '16 at 17:55
  • @Bergi Now, _that_ makes sense. Thanks! –  Mar 23 '16 at 17:57

1 Answers1

0

As you are using $(this).attr mutliple times it means jQuery has to perform the selection of this several times.

It would be better to create a variable for the $(this).attr('id') once as you only need to perform the methods needed to get the attr once.

Also make sure to use a local variable for this attribute ID

Mitch Lamers
  • 126
  • 4
  • Thank you! Exactly the information I was looking for. I'd up-vote but I can't figure out how to get the rep to do so. Anyways, thanks again! –  Mar 23 '16 at 17:48
  • You don't need rep. Just click the tick next to the answer @stackovertroll – Andy Mar 23 '16 at 17:52
  • Oh. Says I need to wait 4 minutes lol. –  Mar 23 '16 at 17:53