.closest()

In this chapter you will learn:

  1. Syntax and Description for .closest()
  2. How to get the first span element for a click event

Syntax and Description

.closest(selector[, context])

gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

selector is a string containing a selector expression to match elements against. context (optional) is a DOM element within which a matching element may be found.

Return value is the new jQuery object.

Get the first span element

The following code gets the first span element after clicking.

<html><!--from ja v  a 2  s.c o  m-->
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
          $(document).bind("click", function (e) {
               $(e.target).closest("span").text("java2s.com");
          });
        });
    </script>
  </head>
  <body>
    <body>
         <div><span>span</span><span>span</span><span>span</span></div>
  </body>
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. Syntax and Description for .contents()
  2. How to get the content of a paragraph
  3. How to wrap the content of a paragraph