$(this) selector

When to use $(this) selector

$(this) selector references the current selected element.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--from w  w w  .  j  a va  2  s .c  om-->
            $("div[id]").one("click", function(){
              var idString = $(this).text() + " = " + $(this).attr("id");
              $(this).text(idString);
            });
        });
    </script>

  </head>
  <body>
    <body>
      <div>no id</div>
      <div id="hey">with id</div>
    </body>
</html>

Click to view the demo

The code above generates the following result.

$(this) selector

Use this() to get next

The following code uses this selector to reference the current event target element and gets the next element by using the next() method. After that it sets the value for the text field.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--from  w  w  w . j  av a2  s.  c om-->
               $("button").click(function () {
                  $(this).next().removeAttr("disabled")
                         .focus()
                         .val("java2s.com now");
               });
        });
    </script>
  </head>
  <body>
    <body>
      <button>Enable</button>
      <input type="text" disabled="disabled" value="can't edit this" />
    </body>
</html>

Click to view the demo

The code above generates the following result.

$(this) selector