-1

Possible Duplicate:
What's the difference between $(this) and this in jQuery?

In jquery selector, the example code is:

<body>
  <select name="garden" multiple="multiple">

    <option>Flowers</option>
    <option selected="selected">Shrubs</option>
    <option>Trees</option>
    <option selected="selected">Bushes</option>

    <option>Grass</option>
    <option>Dirt</option>
  </select>
  <div></div>
<script>

    $("select").change(function () {
          var str = "";
          $("select option:selected").each(function () {
                str += $(this).text() + " "; // I interested it this line
              });
          $("div").text(str);
        })
        .trigger('change');
</script>

</body>

In the example code, there is a portion of code:

str += $(this).text() + " ";

I am wondering, why here does not use str += this.text() + " ";? In another word, why not use this but use $(this) in that portion of code? what is the difference between this and $(this) in this circumstance?

Community
  • 1
  • 1
Leem
  • 17,220
  • 36
  • 109
  • 159
  • 1
    Duplicate of [What's the difference between $(this) and this in jQuery?](http://stackoverflow.com/questions/3685508/whats-the-difference-between-this-and-this-in-jquery) and/or [jQuery $(this) vs this](http://stackoverflow.com/questions/1051782/jquery-this-vs-this) and/or a few others :-) – T.J. Crowder Jun 26 '11 at 13:21

4 Answers4

3

jQuery's each function sets this to the raw DOM element for each call to the iteration callback (docs). Calling $() on that raw element gives you a jQuery object wrapped around it, giving you access to the jQuery functions such as text.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

this is a standard javascript obect, $(this) is the jQuery-wrapped object, exposing all the jQuery goodness like functions and properties that regular JavaScript does not.

Sometimes the jQuery wrapper is not needed, and could be considered overkill.

Neil N
  • 24,862
  • 16
  • 85
  • 145
0

For the same reason you use $("select") and not select. It puts the object into proper jQuery context and returns the jQuery-wrapped object(s).

Kon
  • 27,113
  • 11
  • 60
  • 86
0

$("this") is jquery and 'this' is javascript.

Bee
  • 12,251
  • 11
  • 46
  • 73