1

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​​​​​​​
Eli
  • 14,779
  • 5
  • 59
  • 77
mix
  • 6,943
  • 15
  • 61
  • 90

3 Answers3

5

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"
});

Colin Brock
  • 21,267
  • 9
  • 46
  • 61
  • yes, i'd tried it with $(this), but got the empty string. is there any way to get the text within an each()? – mix Jul 10 '12 at 02:54
  • @mix: Yes, if you want the text of each element, use `.text()`. I'll update my answer. – Colin Brock Jul 10 '12 at 02:55
  • sorry, i mean the selector property text (in this case, '.tst') – mix Jul 10 '12 at 02:55
  • @mix: One option would be to cache the selector (Perhaps someone else has a better idea). I'll update with an example. – Colin Brock Jul 10 '12 at 03:03
  • 1
    Note (for OP): There are lots of ways to create jQuery objects such that the concept of `selector` doesn't make sense (e.g., by combining several other jQuery objects), so writing code that actually _needs_ to test the `selector` is generally not a good plan. – nnnnnn Jul 10 '12 at 04:00
2

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.

nbrooks
  • 18,126
  • 5
  • 54
  • 66
1

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
Community
  • 1
  • 1
Tats_innit
  • 33,991
  • 10
  • 71
  • 77