Jivan
Jivan

Reputation: 1413

Simply which perform faster "click target" or "DOM matches"

What i am trying here to select a parent div with #missingRecord. Which performs better keeping CPU low :D

Click Target:

 if ( $(e.target).parents("#missingRecord").length) { 

        }

Dom matches

if($(this).closest().attr("id") == "missingRecord") {



}

Upvotes: 0

Views: 58

Answers (1)

void
void

Reputation: 36703

Let me tell you, e.target and this doest not alway represent the same object.

And i don't think e.target and this will have any performance difference. As accessing a variable is a very very low computation operation (though that depends on the size of variable)

Let me tell you the difference though between $(this) and event.target, and quite a significant one. While this (or event.currentTarget, see below) always refers to the DOM element the listener was attached to, event.target is the actual DOM element that was clicked. Remember that due to event bubbling, if you have

<div class="outer">
  <div class="inner"></div>
</div>

and attach click listener to the outer div

$('.outer').click( handler );

then the handler will be invoked when you click inside the outer div as well as the inner one (unless you have other code that handles the event on the inner div and stops propagation).

In such a case, inside the handler, this (and event.currentTarget) would refer to the .outer DOM element, and event.target would refer to the .inner element.

The jQuery wrapper $(this) only wraps the DOM element in a jQuery object so you can call jQuery functions on it. You can do the same with $(event.target).

Also note that if you rebind the context of this (e.g. if you use Backbone it's done automatically), it will point to something else. You can always get the actual DOM element from event.currentTarget.

Source

Upvotes: 1

Related Questions