jQuery $(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 . jav a  2s .c  o  m-->
            $("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

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(){<!--  ww w  .  j a v a 2 s  .  c  o  m-->
               $("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





















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities