4thSpace
4thSpace

Reputation: 44310

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.

Upvotes: 2

Views: 97

Answers (4)

AmmarCSE
AmmarCSE

Reputation: 30557

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.

Upvotes: 3

albert hou
albert hou

Reputation: 66

And use this the jQuery no need to do the selection job. So this will be fast than selector

Upvotes: 1

Jaromanda X
Jaromanda X

Reputation: 1

ID can change (why you would is another matter)

consider:

$("#firstname").click(function() {
    $("#firstname").val("changed");
})[0].id="somethingElse";

vs

$("#firstname").click(function() {
    $(this).val("changed");
})[0].id="somethingElse";

Upvotes: 0

ded
ded

Reputation: 1350

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.

Upvotes: 5

Related Questions