Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .last().hide().fadeIn() fading in all items in the list

$('#mainlist').last().hide().fadeIn(200);

Why is this hiding, and then fading in all the items in the list instead of just the last one?

Edit: The section of HTML:

<div id="mainbox">
    <ul id = "mainlist">

    </ul>
</div>

My js appends to the ul with a li, and then it runs the first code shown above.

like image 734
JakAttk123 Avatar asked Dec 05 '25 06:12

JakAttk123


2 Answers

It's because there's only one element in the list returned by $("#mainlist"). You're selecting the last #mainlist which is your ul.

The .last() method selects the last element in a list of DOM elements, not the last child of the elements selected.

From the jQuery docs:

Given a jQuery object that represents a set of DOM elements, the .last() method constructs a new jQuery object from the last element in that set.

You want something like $('#mainlist li').last().hide().fadeIn(200); instead.

like image 145
Joundill Avatar answered Dec 07 '25 20:12

Joundill


It's because your #mainlist element has another child/wrapping <ul> before the list items (so it's hiding the wrapping <ul>, thus all the elements). Maybe try be more specific with your selector

$("#mainlist li").last().hide().fadeIn(200);

EDIT By the way, this assumes your <ul> is filled with <li> tags.

like image 25
Nick Bull Avatar answered Dec 07 '25 22:12

Nick Bull



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!