Search code examples
javascriptjqueryhtmlcsshref

hide href element in specific UL with javascript


How we can hide href element in specific UL element ( not in all UL elements, because UL elements are with the same name).

For example we have HTML code like this:

<ul class="UL_tag">
  <li>Text 1</li>
  <li>Text 2</li> 
  <li><a href="http://www.google.com" class="description">Link to GOOGLE</a></li>
</ul>   

<ul class="UL_tag">
  <li>Text 1</li>
  <li>Text 2</li> 
  <li><a href="http://www.yahoo.com" class="description">Link to Yahoo</a></li>
</ul>   

And we can hide these href's by using this code:

$('a.description').hide();

How should I change this javascript code, if I want to hide just one href element which is in the one UL element? Not all href elements with the class name "description" ?

Thank you for your help!


Solution

  • You can traverse the dom to get the element within the parent ul

    $(this).parent().siblings().find('a.description').hide();
    // get current clicked > parent li > siblings > find a.description in li siblings > hide
    

    http://jsfiddle.net/CjfXu/1/

    EDIT

    Since your li is actually wrapped inside a span also.. .parent won't work as it's getting the span element. You need to use .closest() - which gets the closest ancestor that matches

    $(this).closest('li').siblings().find('.description').hide();
    

    Also don't bind a click event inside another click event as that causes the dom to attach multiple event handlers to the element. Always bind inside the document.ready function. Dynamically created elements or when you have many elements that you need to bind, using delegation would be the most efficient way.

    You had your code like this

    $('a.start').bind('click', function(){ // <-- this should be $('a:not(.start)').bind 
         // code
    
         $('a.start').click(function(e) {            
             $(this).parent().siblings().find('.description').hide();
         });            
    
    });
    

    Which is binding any anchors with class=start a click event each time the first anchor is clicked

    to use delegation

    $('parentElement').on('click','element', function(){
    
    })
    

    or jQuery 1.6 and below

    $('parentElement').delegate('element','click', function(){
    
    });