views:

19

answers:

1

This has got to be an easy one...

I have a list. I want to show the one element in each list item, with an option to see more (if there are any). Like this:

<li class="item">
  <div class="elementToShow">Shown Element</div>
  <div class="elementsToBeHidden">Hidden Element</div>
</li>
<li class="item">
  <div class="elementToShow">Shown Element</div>
</li>
<li class="item">
  <div class="elementToShow">Shown Element</div>
  <div class="elementsToBeHidden">Hidden Element</div>
</li>

I then want to add a button in jQuery to expose the other elements:

$('.item).children('.elementsToBeHidden')
  .wrapAll('<div class="hiddenElements"></div>');
$('<a class="hiddenElements"> See More </a>')
  .appendTo($('.hiddenElements'))
  .click(function() {
    $('.elementsToBeHidden').slideToggle('slow');
  });

This, though, groups all the hidden elements under the first list item.

What is missing if I want to show the first hidden element in the first item and the third in the third item?

With thanks in advance for any help.

+2  A: 

Why bother wrapping them when they have a class?

Try this: http://jsfiddle.net/GEJ29/2/

$('.item:has(.elementsToBeHidden)').append('<a class="hiddenElements"> See More </a>')
    .find('a').click(function() {
    $(this).siblings('.elementsToBeHidden').slideToggle('slow');
});​

or the same thing, but a little better in my opinion:

http://jsfiddle.net/GEJ29/3/

$('<a class="hiddenElements"> See More </a>').appendTo('.item:has(.elementsToBeHidden)')
    .click(function() {
        $(this).siblings('.elementsToBeHidden').slideToggle('slow');
});​

Original answer:

You want to operate on each <li> individually.

Try this: http://jsfiddle.net/wQ2V6/

$('.item').each(function() {
    $(this).children('.elementsToBeHidden')
        .wrapAll('<div class="hiddenElements"></div>');

    $('<a class="hiddenElements"> See More </a>')
        .appendTo($(this).find('.hiddenElements'))
        .click(function() {
            $(this).siblings('.elementsToBeHidden').slideToggle('slow');
        });

});
patrick dw
Thank you very much. Not one but two helpful answers.
lazysoundsystem
@lazysoundsystem - You're welcome. :o)
patrick dw