Sam
Sam

Reputation: 13

this.parent toggleClass of another child div

I am new to jQuery and I can't figure this out.

When I click on the first toggleButton, I would like to target the first textContainerCollapsed and toggle its class with textContainerExpanded. And if I click on the second toggleButton, I would like the second textContainerCollapsed to toggle its class with textContainerExpanded and so on...

However, the result I have been getting is that all divs with the textContainerCollapsed are being affected regardless of which toggleButton I click.

js

$(function() {
    $(".toogleButton") click(function() {

        $(".textContainerCollapsed").toogleClass("textContainerExpanded",500);

        //Also tried
        //$(this).parent(".textContainerCollapsed").toogleClass("textContainerExpanded",500);

        //Also tried
        //$(this).parent.children(".textContainerCollapsed").toogleClass("textContainerExpanded",500);

        //Also tried
        //$(this).parent.next(".textContainerCollapsed").toogleClass("textContainerExpanded",500);

        //Also tried
        //$(this).parent(".parent").next(".textContainerCollapsed").toogleClass("textContainerExpanded",500);

        //Also tried
        //$(this).parent(".parent").children(".textContainerCollapsed").toogleClass("textContainerExpanded",500);

        //Also tried
        //$(this).parent(".parent").find(".textContainerCollapsed").toogleClass("textContainerExpanded",500);

    });
});

html

<div class="parent">
    <div class="buttonContainer">
        <a href="#" class="toogleButton">
    </div>
    <div class="textContainerCollapsed">
        Some text
    </div>
</div>
<div class="parent">
    <div class="buttonContainer">
        <a href="#" class="toogleButton">
    </div>
    <div class="textContainerCollapsed">
        Some text
    </div>
</div>

css

.textContainerCollapsed
{
    height: 0px;
    overflow: hidden;
}
.textContainerExpanded
{
    height: 100%;
    overflow: hidden;
}

Upvotes: 0

Views: 360

Answers (2)

billyonecan
billyonecan

Reputation: 20270

$('.toogleButton').click(function() {
    $(this).parent().next()
           .toggleClass('textContainerCollapsed textContainerExpanded');
});

Upvotes: 0

VisioN
VisioN

Reputation: 145458

1st version using closest() and find():

$(this)
  .closest(".parent")
  .find(".textContainerCollapsed")
  .toogleClass("textContainerExpanded");

2nd version using parent() and next():

$(this)
  .parent()
  .next()
  .toogleClass("textContainerExpanded");

3rd version using parent() and siblings():

$(this)
  .parent()
  .siblings()
  .toogleClass("textContainerExpanded");

Upvotes: 1

Related Questions