markzzz
markzzz

Reputation: 47945

What's wrong with this .end() function?

This is my code :

<a href="javascript:void(0);" id="apri-menu">
    <span>First</span>
    <span style="display:none;">Second</span>
</a>​

$('#apri-menu').click(function () {
    $(this).find('span').first().hide().end().find('span').last().show();
    $('#menu-nascosto').show();
});​

clicking on the link I'd aspect to show the second span, but seems that .end() make some pain.

Where am I wrong?

Upvotes: 2

Views: 85

Answers (3)

Tats_innit
Tats_innit

Reputation: 34107

working demo http://jsfiddle.net/KqdJS/

You can go back to the parent .end().parent() and then show it,

You can also see the responses above, hope this helps :)

code

$('#apri-menu').click(function () {
    $(this).find('span').first().hide().end().parent().find('span').last().show();

    $('#menu-nascosto').show();
});​

Upvotes: 0

xdazz
xdazz

Reputation: 160833

Try the below way. The reason is as @Jon said.

$(this).find('span:first').hide().end().find('span:last').show();

Upvotes: 1

Jon
Jon

Reputation: 437376

What .end() does is "return the jQuery object to its previous selection state". In your example, the last operation that modifies the matched objects is .first(), so .end() rewinds time back to just before that -- after .find('span'). So the end result is as if you had written

$(this).find('span').find('span').last().show();

...which will obviously not work because there are no nested <span>s in your markup.

Simply getting rid of the second .find() will fix things.

Upvotes: 4

Related Questions