Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selector vs this in jQuery

Is there any reason to use an ID vs "this" in the following examples:

$("#firstname").click(function() {
    $("#firstname").val("changed");
});

vs:

$("#firstname").click(function() {
    $(this).val("changed");
});

Outcome is the same either way.

like image 923
4thSpace Avatar asked Nov 23 '25 11:11

4thSpace


2 Answers

The idea is that if you change firstname above, you won't have to change it again in the second block. Eg:

$("#my-new-name").click(function() {
  // "this" remains the same.
  $(this).val("changed");
});

Also, performance-wise, jQuery will not need to parse the string and run through its selector engine, and instead this is a raw DOMElement that it can quickly detect its type and get on its way.

like image 122
ded Avatar answered Nov 25 '25 01:11

ded


One reason to use this rather than the id is performance.

When you enter the click handler, this already exists and is set.

Therefore, I imagine it is much faster to create a jQuery object with this rather than invoking sizzle, the selector engine, to find that element by id and create the jQuery object

Another reason for choosing this is semantics. Semantically, this is easier to read in context when I enter the click handler. This is because I already know that the handler is for #firstname. However, if I see an id selector, I have to double check and make sure both the handler selector and the id selector are one and the same.

like image 38
AmmarCSE Avatar answered Nov 25 '25 00:11

AmmarCSE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!