Reputation: 12693
For Example, this will give me:
console.log($(".smartgridview-normal").selector)
//result is '.smartgridview-normal'.
My code is :
$( '.smartgridview-normal th' ).live( 'dblclick', function () {
var optimalWidth = parseFloat( $( this ).attr( 'data-width' ) );
console.log( $(this).selector );// At this point I need the selector
$(this).addClass('selected');
} );
My Log is giving me an empty string. There is no selector for 'this' object. Is there any way to get the selector of the element which 'this' is pointing to?
Thanks for your time.
Upvotes: 1
Views: 8965
Reputation: 11470
Perhaps set it to a variable first?
var sel = "answer";
$("#"+sel).on("dblclick", function(event){
console.log("Current selector is "+sel);
});
Upvotes: -2
Reputation: 10685
As Amadan said, inside the click handler this
refers to the element, not the jQuery object
It's not perfect, but you could cache the jQuery object
var elements = $("#mySelector")
$elements.on("dblclick", function(event){
console.log($elements.selector);
});
Fiddle for testing
Upvotes: 2
Reputation: 28174
To elaborate on my comment, "#"+this.id
is the best you can hope for if the element has an id. If not, the only information you have is that the element belongs to your original selection '.smartgridview-normal th'
.
You could always add the id yourself within the code (for example unique id based on the current date and time).
Upvotes: 1
Reputation: 17930
Try using nodeName
instead of selector
,
var selector = $(this)[0].nodeName;
Or,
var selector = this.nodeName;
Upvotes: -2
Reputation: 198526
Oh, I see where your problem is. $(this)
is not constructed using a selector, but rather by directly wrapping a DOM element, so it does not carry it anywhere. You can get the original selector obviously by doing $('.smartgridview-normal th').selector
; but there's a big difference between $('.smartgridview-normal th')
and $(this)
.
Upvotes: 2