vivianh
vivianh

Reputation: 155

how to select the right div in javascript using parent/child

I have a couple different divs that all look about like this.

$(document).ready(function() {
  $(".show").click(function() {
    $(".show").parent().(".text").toggle();
  });
});

<div class="container #{i}">
    <div class="show">
        show
    </div>

    <div class="text">
        text text text
    </div>
</div>

I want to be able to click show, and have it only toggle the text div within its container div. I thought I could grab the parent of the element with class "show" I clicked on, which would be container + index, and then get the child class called "text" in that container div.

This honestly feels fairly trivial, but I'm not very experienced in Javascript yet, and I wasn't sure of the wording to search for. I would greatly appreciate any help. :)

Upvotes: 2

Views: 435

Answers (5)

Icarus
Icarus

Reputation: 63970

You are very close, you just need to call "find" on the parent and replace the .show selector for this since you only want to toggle the .text divs inside the current (this) parent and not across the board. So you need something like this:

$(document).ready(function() {
  $(".show").click(function() {
    $(this).parent().find(".text").toggle(); //replaced .show for this
  });
});

Or another alternative (although someone else already posted it)

$(".show").siblings(".text").toggle();

However, for the above to work, both divs (.show and .text) must be at the same level whereas find, will find it even if .text is nested inside another element.

Upvotes: 1

Mohamed Habib
Mohamed Habib

Reputation: 903

you can try this inside .click function

$(this).parent().find("text").toggle();

Upvotes: 0

veddermatic
veddermatic

Reputation: 1082

You can use the siblings function to get / filter elements on the same level:

jQuery('.show').click( function () {
   jQuery(this).siblings('.text').toggle(); 
});

More info: http://api.jquery.com/siblings/

Upvotes: 1

Jeff Shaver
Jeff Shaver

Reputation: 3355

You shouldn't have to grab the parent...

$('.show').click(function() {
    $(this).next().toggle()
});

should work. Just grabs the sibling.

Upvotes: 0

jcubic
jcubic

Reputation: 66650

There is find function for that

$(document).ready(function() {
  $(".show").click(function() {
    $(this).parent().find(".text").toggle();
  });
});

Upvotes: 3

Related Questions