Handle the event with .click and then use the .parent and .hide methods.
$("a").click(function(){
$(this).parent().hide(); // this is the link element that was clicked
})
The code above assumes that the link is contained directly in the list element (<li>
). If that isn't the case you can pass a selector to the .parent
method like this:
$(this).parent("li").hide();
This will find go through the ancestors of your link and return the one that is a <li>
.
Returning false
Normally, when you click an <a>
tag the browser will navigate to the href of the tag. If you don't want that you can either return false;
from the click handler or add an href that returns false: <a href="javascript:void(0)">Link</a>
. There's more discussion about this in this question.
There are many different ways to do this
You might need variations of the code because:
- You probably have other links on the page that you don't want to hide the parent of. This is why it makes sense to use "ul li a" as the selector instead of "a" - it will only match the links that are inside a list
- You can use the
.preventDefault()
of the event object instead of returning false to prevent the browser from changing the address
- Since the link will be hidden after being clicked you can also use the .one method - it will remove the event handler after the link has been clicked. Don't do this if you plan to show the link again later on.
- You can use .on instead of
.click
if your list is dynamic, i.e. you will use Javascript to add links to it
- Some answerers have wrapped the code in what's called a self-invoking function. It looks like this:
(function() { /* code */})(jQuery);
. I would not recommend this for beginners, although it will help you structure your code later on. Basically it helps you avoid unwanted side-effects in your code and allows you to use .noConflict.