Seemax
Seemax

Reputation: 121

$(this) throws "undefined" but this works as intended

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

Upvotes: 1

Views: 279

Answers (2)

oriadam
oriadam

Reputation: 8549

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();

Upvotes: 2

Prabhat-VS
Prabhat-VS

Reputation: 1530

$() 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.

Upvotes: 0

Related Questions