closest method in Jquery

General discussion on technical and managerial topics
no avatar
mlotfi
 
Posts: 1
Joined: Mon Apr 23, 2012 3:17 am
Location: United States

closest method in Jquery

by mlotfi » Mon Apr 23, 2012 3:34 am

Hi,
I just started learning Jquery, I found this tutorial :

http://www.tutorialspoint.com/jquery/tr ... losest.htm

it said :

Description:
The closest( selector ) method works by first looking at the current element to see if it matches the specified expression, if so it just returns the element itself. If it doesn't match then it will continue to traverse up the document, parent by parent, until an element is found that matches the specified expression. If no matching element is found then none will be returned.

Code: Select all
<html>
<head>
<title>the title</title>
   <script type="text/javascript"
   src="/jquery/jquery-1.3.2.min.js"></script>
 <script>
  $(document).ready(function(){

    $(document).bind("click", function (e) {
      $(e.target).closest("li").toggleClass("highlight");
    });

  });
  </script>
  <style>
  .highlight { color:red;
          background: yellow;
        }
  </style>
</head>
<body>
   <div>
   <p>Click any item below to see the result:</p>
   <ul>
     <li class="top">list item 1</li>
     <li class="top">list item 2</li>
     <li class="middle">list item 3</li>
     <li class="middle">list item 4</li>
     <li class="bottom">list item 5</li>
     <li class="bottom">list item 6</li>
   </ul>
   </div>
</body>
</html>


when you click in a list item it change its class.
what I did now, changed :
Code: Select all
<script>
  $(document).ready(function(){
    $(document).bind("click", function (e) {
      $(e.target).closest("div").toggleClass("highlight");
    });
  });
  </script>


AND

Code: Select all
<body>
   <div class="someclass">
   <p>Click any item below to see the result:</p>
   <ul>
     <li class="top">list item 1</li>
     <li class="top">list item 2</li>
     <li class="middle">list item 3</li>
     <li class="middle">list item 4</li>
     <li class="bottom">list item 5</li>
     <li class="bottom">list item 6</li>
   </ul>
   </div>
</body>


since div is one of the li parent, so clicking in any li should change the class of div to yellow, but it does not work, maybe I misunderstood how this function works or I am missing something.

your help is appreciated.

no avatar
mcloren
 
Posts: 7
Joined: Thu Jan 03, 2013 9:22 pm

»

by mcloren » Wed Jan 30, 2013 10:58 am

http://www.bennadel.com/blog/1728-jQuer ... cestor.htm
I have found it. hope it will be useful for you

Return to General Discussion