pershianix
pershianix

Reputation: 97

Proper jQuery chaining

I'm trying to chain this piece of code:

$('.testslides :first-child').fadeOut();
$('.restslides :last-child').prependTo('.slides').fadeIn();

into this:

$('.testslides :first-child').fadeOut().find('.slide last-child').prependTo('.slides').fadeIn();

but it doesn't work. where am I doing it wrong? Thank you.

Upvotes: 0

Views: 43

Answers (2)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

You may use .first() and .last() combining .end() method:

$('.slides').first().fadeOut().end().last().prependTo('.slides').fadeIn();

Upvotes: 2

rrk
rrk

Reputation: 15846

Your problem was $('.slides :first-child') will get all the children elements, which is a first-child of any of the inner html elements.

So use .children() then .eq(0) to get the children and take the first one from them. As an alternative CSS selector $('.slides > :first-child').

find() is used to find the children of an element. Use either

  1. parent() then children()
  2. closest('.slides') then children()
  3. siblings()

and get the last() item.

$('.slides').children().eq(0).fadeOut()
     .siblings().last().prependTo('.slides').fadeIn();

Upvotes: 2

Related Questions