mix
mix

Reputation: 7151

why is jQuery selector property undefined within each()?

Given the following code, why does the selector property work in the first instance but not the second? Aren't they both jQuery objects?

<span class='tst'>span</span>​

var tst = $('.tst');
console.log(tst.selector); 
// prints '.tst'

$('.tst').each(function() { console.log(this.selector);});
// prints undefined​​​​​​​

Upvotes: 1

Views: 1211

Answers (3)

nbrooks
nbrooks

Reputation: 18233

this != $(this)

In your first case tst is a reference to the jQuery object, but in the second this is simply the corresponding DOM element.

Within an .each() loop the .selector property is not available, however. To access '.tst' you can do $(this).attr("class") (when you use a class selector) -- though if you already use it in the each you can just cache it in a variable before hand.

Note that this will return all of the classes for that elements, so you can parse it later if it has more than one.

The best workaround based on your exact description is this:

var $tst = $(".tst");
$tst.each(function() {
    console.log($tst.selector); //prints .tst
});

However I can't see any reason why you really need to do this.

Upvotes: 2

Colin Brock
Colin Brock

Reputation: 21575

this, in the context of the .each() loop, is not a jQuery object, so the selector property is undefined.

You need to make it a jQuery object first: $(this).selector

However, it should be noted that the selector property will return an empty string while inside the .each() loop.

Edit

If you absolutely need the selector property within the .each(), one option would be to cache your selector:

var cached = $('.tst');

cached.each(function() { 
    console.log(cached.selector); // Will display ".tst"
});

Upvotes: 5

Tats_innit
Tats_innit

Reputation: 34107

Working Demo http://jsfiddle.net/wA6Yv/ or http://jsfiddle.net/a3CYR/2/

this != $(this)

If you keen: jQuery: What's the difference between '$(this)' and 'this'?

code

var tst = $('.tst');
console.log(tst.selector);
// prints '.tst'
$('.tst').each(function() {
    alert($(this).text());
});
// prints undefined

Upvotes: 1

Related Questions