Search code examples
javascriptjquerytraversal

jQuery get parent sibling for this element only


I cant figure out how to write this.

See my mark up structure, which is repeated multiple times on a page.

<div class="module">    
    <div class="archive-info">
        <span class="archive-meta">
            open
        </span>                         
    </div>
    <div class="archive-meta-slide">
    </div>                              
</div>

As you can see inside my mark-up, I have a <span> which is my $metaButton - when this is clicked, it runs the animation on the div.archive-meta-slide - this is simple enough, but I'm trying to run the animation only on the current div.module it animates all the divs with the class "archive-meta-slide", and I'm really struggling to animate only the current div.archive-meta-slide using this

It would be easy if the div.archive-meta-slide was inside the parent div of $metaButton, but because it's outside this parent div, I can't get the traversing right.

See my script

var $metaButton = $("span.archive-meta"),
    $metaSlide = $(".archive-meta-slide");

$metaButton.toggle(
function() {
    $(this).parent().siblings().find(".archive-meta-slide").animate({ height: "0" }, 300);
    $(this).parent().siblings().find(".archive-meta-slide").html("close");
},
function() {
    $(this).parent().siblings().find(".archive-meta-slide").animate({ height: "43px" }, 300);
    $(this).parent().siblings().find(".archive-meta-slide").html("open");
});

Can anyone help?

Thanks Josh


Solution

  • $(this).parent().siblings().find(".archive-meta-slide")  
    

    This is really close. This actually says "find elements with the class archive-meta-slide that are descendants of siblings of this element's parent". You want to say "find elements with the class archive-meta-slide that are siblings of this element's parent". For that, use a selector on the siblings call:

    $(this).parent().siblings(".archive-meta-slide")  
    

    Note that, if the markup is always this structure, you could even do $(this).parent().next().

    See the jQuery API: