jeffreynolte
jeffreynolte

Reputation: 3779

jQuery targeting specific links in an optimal way

Note: This is more of a best how rather than how question.

I have several links within a ul that I would like to target but not every single a tag. While I know I can target each element by ID I would like to know what is best practice (most optimized selceting, smallest amount of code) for this task.

   $("#id").find("a").click(function(){
  //run function                    
});     

markup:

    <nav id="id">    
  <ul>
    <li id="want-01"><a href="#">link</a></li>
    <li id="want-02"><a href="#">link</a></li>
    <li id="want-03"><a href="#">link</a></li>
    <li id="dont-want-01"><a href="#">link</a></li>
    <li id="dont-want-02"><a href="#">link</a></li>
    <li id="want-04"><a href="#">link</a></li>
    <li id="want-05"><a href="#">link</a></li>
  </ul>       
</nav>

Upvotes: 0

Views: 348

Answers (3)

bcm
bcm

Reputation: 5500

$("#id").find("a").not("#dont-want-01 a, #dont-want-02 a").click(function(){   

});   

Upvotes: 1

jbcurtin
jbcurtin

Reputation: 1803

Theres' really no way to do it with that HTML, but if you implmented a rel attr or class you can select it fairly easily.

   <nav id="id">    
  <ul>
    <li id="want-01" rel="wanted"><a href="#">link</a></li>
    <li id="want-02" rel="wanted"><a href="#">link</a></li>
    <li id="want-03" rel="wanted"><a href="#">link</a></li>
    <li id="dont-want-01"><a href="#">link</a></li>
    <li id="dont-want-02"><a href="#">link</a></li>
    <li id="want-04" rel="wanted"> <a href="#">link</a></li>
    <li id="want-05" rel="wanted"><a href="#">link</a></li>
  </ul>       
</nav>

$("#id").find('li[rel=wanted]').children();

Upvotes: 0

a&#39;r
a&#39;r

Reputation: 36999

The use of a class would seem appropriate here. Create a new class say 'li_link' and add it to the li elements that you want to link to. Then apply your click handler to all li elments with the class, eg.

$('.li_link').click(function() {...});

If you want to change the li elements that are handled dynamically, you could consider using live events. This allows you to add and remove the 'li_link' class from li elements and the click handler will apply or stop being applied to the li elements automatically.

To set up a live event use something like this:

 $('.li_link').live('click', function() {...});

Upvotes: 2

Related Questions