Difference between $(this) and this in jQuery

this refers to a to a DOM element and $(this) refers to a jQuery object.
In other word if you use this you have to use javascrip code, But if you use $(this) you have to use jQuery code.

As we know that innerText is javascrip method where as text() is jQuery method, so we can use innerText with this but we can not use text() with this

CODE
<!DOCTYPE html>
<html>
<head>
  <title>jQuery With Example</title>
  <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(function () {
      $('#divTest').click(function () {
        alert("First case " + this.innerText);
        alert("Second case: " + $(this).text());
      });

    });
  </script>
</head>
<body>
  <div>
    <div id="divTest"><a>Click here to see difference</a></div>
  </div>
</body>
</html>
DISPLAY

8 comments :

  1. When I am using Firefox (33.0) the first case give me "undefined" but the example runs fine in Internet Explorer and Chrome!

    ReplyDelete
    Replies
    1. Hi,
      Firefox support textContent instead of innerText. So use jQuery because it is multi-browser supported.

      Please click below to read following article.
      Difference between jQuery and JavaScript

      Delete
    2. Yes that's right, even I was not able to get the content using the innerText, so this how jQuery is useful as the text() behavior was consistent throughout all the browser.

      Delete
  2. Nice Example. Spent much time to understand the difference, finally I got it here. Thanks!

    ReplyDelete
  3. Great Example................... Thanks a lot..

    ReplyDelete
  4. Hi, I agree with your description with the difference between the both. But a tutor who teaches jQuery, said '$(this)' can be used only in jQuery, whereas 'this' can be used in both JavaScript and jQuery. Is that possible??

    ReplyDelete
    Replies
    1. Yes you can use "this" in both because jQuery develop on javascript code.

      Delete