views:

103

answers:

4

I'm new at jQuery (just picked up a book this morning!) and I'm trying to hide an element; it doesn't seem to be working.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"&gt;
<html>
    <head>
     <title>Test</title>

     <script type="text/javascript" src="javascript/jquery-1.3.2.min.js"></script>
     <script type="text/javascript">
      if ($) {
       $(document).ready(

        function() {

         $('ul li span').click(

          function() {
           $(this).parent().children('ul').hide();
          }

         );

        }

       );
      }
     </script>

    </head>
    <body>

      <ul>      
       <li><a href="">My Controls <span class="arrow">&uarr;</span></a>
        <ul>
         <li><a href="">My Profile</a></li>  
        </ul>  
       </li>
      </ul>

    </body>
</html>

This is the full code I'm using. When I click the span tag I want it to hide the inner <ul>. I assumed that this would access the span element, parent() the li, and children() the ul contained instead the li, but this doesn't seem to be the case. Am I making some sort of stupid mistake here?

TIA.

+2  A: 

When you click on the span you get the parent of the spam (the a) and look for its ul children — it doesn't have any.

You need to go up another level.

David Dorward
Using `$(this).parent().parent().children('ul').hide();` doesn't seem to work either, assuming that's how you do it. It does make the child `ul` flash, but not stay hidden.
James Inman
A: 

'this' represents DOM element. You need jQuery wrapper for it, $(this). Try

$(this).parent().children('ul').hide();
Roman
Sorry, that was an error when I copied across - fixed and it still doesn't work.
James Inman
+1  A: 

You can shorten this by navigating directly to the parent (note: parents('selector') climbs the ancestors until a match, no more .parent().parent()... guessing):

$(this).parents('li').find('ul').hide();

Also, I suggest this for more effect:

$(this).parents('li').find('ul').slideUp();

Your ul elements aren't children of your span or your anchor, they're children of the li they both belong to. Traversing up to this then hiding all ul beneath is what you're after I believe.

Nick Craver
+1  A: 

The following works, clicking the arrow (and only by clicking the arrow, though I suspect that's intentional on your part), hides the child <ul>, in FF3.0.12, Ubuntu 8.04. Though for some reason it seems unnecessarily complex.

<script type="text/javascript">
 if ($) {
  $(document).ready(

   function() {

    $('ul li span').click(

     function() {

          $(this).parent().parent().children('ul').hide(); // Original (modified) technique

// Nick's technique: $(this).parents('li').find('ul').hide();
// My preferred technique: $(this).parents('li').find('ul').toggle();
         }

    );

   }

  );
 }
</script>
David Thomas