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>
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.
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: