1

Please, consider two pieces of code.

1) Works as intended:

  $(function(){
    $('.menu  li').on('click', function(){
    var choice = document.getElementById("choice");
    var text = this.textContent;
      choice.textContent = text;
    });
     });

2) In this case, $(this) throws "undefined".

$(function(){
$('.menu  li').on('click', function(){
var choice = document.getElementById("choice");
var text = $(this).textContent;
  choice.textContent = text;
});
 });

I've been using $(this) as a reference to selected element for a long period of time. But today it failed. What's wrong? Should I forget about $(this) and never more be facing such a case in a few lines of simple code?

Codepen

Rino Raj
  • 6,264
  • 2
  • 27
  • 42
Seemax
  • 121
  • 12

2 Answers2

2

The .textContent is a DOM property, not a jQuery property or method. This is why $(this), which is a jQuery element, does not have it.

You can use $(this)[0] to get the actual DOM property out of the jQuery element, like that:

var text = $(this)[0].textContent;

However $(this)[0] is equivalent to this so there's no point doing so in that specific example. It might make sense in other cases - for example, if you get a jQuery element as a function argument:

function set_text(jqElem,txt) { jqElem[0].textContent = txt; }

You can also use the jQuery method .text() to get or set the text content of the element, like that:

var text = $(this).text();
oriadam
  • 7,747
  • 2
  • 50
  • 48
  • May I assume that using this vs $(this), as a DOM method is the best way to avoid confusion if someone forgets the difference between DOM property and jQuery method? – Seemax Apr 11 '16 at 13:30
  • @ВладимирМаксименко Mixing DOM and jQuery elements is acceptable, it is mainstream. The reason is that jQuery elements are easier to use in many cases. However, when a simple DOM property is available for something, like the `.textContent`, it is much faster to use it than wrapping elements as jQuery elements. In this example one should use `this.textContent` because wrapping the `this` with `$(this)` cause an unnecessary processing. – oriadam Apr 24 '16 at 11:16
0

$() is the jQuery constructor function.

but this is a reference to the DOM element of invocation.

$(this), you are just passing the this in $() as a parameter so that you could call jQuery methods and functions.

Prabhat Sinha
  • 1,500
  • 20
  • 32