alopez02
alopez02

Reputation: 1524

Traverse down to the next element down not immediate and of different type

So in an html structure like this:

    <a class="member-main">
      <!-- other divs and html elements -->
    </a>

    <div class="hidden-group-item">
      <!-- other divs and html elements -->
    </div>

I want to bind a click event to an html element with class .member-main so to show a hidden element .hidden-group-item.

There are plenty of those elements repeated in the page in pairs so I'd also like to show only that .hidden-group-item immediately below its respective .member-main

I'm aiming to do so with a function like below, helped by this previous question:

$('body').on('click', '.member-main', function() {
    $(this).next('.hidden-group-item')[0].toggleClass('hide')
});

I can get the element associated on click through this keyword (if I console log it), but I can't seem to grab that node that'd let me traverse down to the hidden-group-item.

How does this work in this case and what would be the most efficient way to achieve this?

Upvotes: 0

Views: 223

Answers (2)

E. Sundin
E. Sundin

Reputation: 4181

This works as expected

The docs about the .next() method says the following:

Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

Because you have the onClick handler and you're selecting the currently clicked element as $(this) then the matched set of elements is only the one you clicked, thus the next() call gets the .hidden-group-item just beneath it.

Sample

$('body').on('click', '.member-main', function() {
  $(this).next('.hidden-group-item').toggleClass('hide')
});
.hide {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<a class="member-main">
  <!-- other divs and html elements -->
  hello
</a>

<div class="hidden-group-item hide">
  <!-- other divs and html elements -->
  hidden
</div>

<a class="member-main">
  <!-- other divs and html elements -->
  hello
</a>

<div class="hidden-group-item hide">
  <!-- other divs and html elements -->
  hidden
</div>

<a class="member-main">
  <!-- other divs and html elements -->
  hello
</a>

<div class="hidden-group-item hide">
  <!-- other divs and html elements -->
  hidden
</div>

JSFiddle

Upvotes: 3

ibrahim mahrir
ibrahim mahrir

Reputation: 31682

...[0] returns a nodeElement not a jQuery object that has the function toggleClass. Try this:

$('body').on('click', '.member-main', function() {
    $(this).next('.hidden-group-item') // next is already returning one item so no need to try to access the first 
           .toggleClass('hide')
});

Upvotes: 3

Related Questions