RollRoll
RollRoll

Reputation: 8462

How to access the current element in a selector?

I want to avoid the overhead of calling $("#) again and wanted to reference the element that is already selected in the selector, something like using this

any help?

$("#aModel1").click(function () {
  alert( ??? .attr("myattribute")  );
});

Upvotes: 0

Views: 42

Answers (3)

Seva Kalashnikov
Seva Kalashnikov

Reputation: 4392

jQuery $(this) will do it

$("#aModel1").click(function () {
    alert( $(this).attr("myattribute")  );
}

Upvotes: 1

Marco Cotrufo
Marco Cotrufo

Reputation: 216

Inside the event handler this is usually binded to the source element:

$("#element").click(function() {
  alert($(this).attr('myattribute'));
});

Or you can save the reference to the element:

var element = $("#element");
element.click(function() {
  alert(element.attr('myattribute'));
});

Upvotes: 0

user5719151
user5719151

Reputation:

Is there a reason you cant use

this

??

$("#aModel1").click(function () {
  alert($(this).attr("myattribute")  );
});

Upvotes: 1

Related Questions