I’m trying to hide a li list item when the link inside is clicked i.s
<ul>
<li id="list_1" class="list"><a href="http://">hide</a>
</li>
<li id="list_2" class="list"><a href="http://">hide</a></li>
<li id="list_3" class="list"><a href="http://">hide</a></li>
<li id="list_4" class="list"><a href="http://">hide</a></li>
</ul>
<span class="updateNumber">0</span>
and everytime a li item is hidden, increase the number of updateNumber text by 1. thanks
This should do the trick:
The selector
li afinds all<a>tags inside any<li>(I’ve kept it simple here so it’ll be greedy). We then use$.on()to bind an event handler to theclickevent.Now we use an anonymous function (a function without a name) to do our stuff in. Here, we pass
einto the function as an argument.econtains the event object so we can doe.preventDefault()on the next line. This line stops the browser doing it’s default behaviour on the link, which is to navigate to the URL in thehrefattribute in the<a>tag.The line
$(this).parent().hide()is the important one. Here,$(this)references the link that was clicked, so doing$(this).parent()we can access the parent node (tag) of the<a>which is an<li>in this case. Adding.hide()to the end of it hides the<li>and you’re done.To update your
.updateNumberspan, add this code to your click handler function:The first line gets an integer from the text within your span and assigns it to a variable called
currentNumber.parseInt()will attempt to turn whatever is inside the span into an integer.The second line
currentNumber++;takes the current value we got from the span and increments it by one (the++) bit.We then want to replace the text displayed in the span with the new, updated value, so we put the new value back into the span by using
$.text()again:Note that using
$.text()without passing it a string to use will retrieve the element’s text, whereas supplying$.text()with an argument such as"Hello world, I'm a string"will put that string into the target element.Here is a working demo proudly produced and sponsored by @Reigel from the comments.