0

I am missing something here. When the row with the class one is clicked, I want to find only the closest row with the class two and then toggle (show/hide) it.

$(".one").on('click', function() {
   $(this).find('.two').toggle(); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr class="one">
        <td> Hello </td>
    </tr>
     <tr>
        <td> world </td>
    </tr>
    <tr class="two">
        <td> Foo </td>
    </tr>
    <tr class="two">
        <td> Bar </td>
    </tr>    
</table>
Neil
  • 4,578
  • 14
  • 70
  • 155
  • 1
    if it is peer to your clickable element you can use `.siblings()` instead of `.find()` https://api.jquery.com/siblings/ - or a different method like `parents` or `closest` or `next` depending on what you want. https://api.jquery.com/category/traversing/tree-traversal/ – lemieuxster Jul 08 '15 at 23:30

2 Answers2

3

Something like this:

$(".one").on('click', function() {
    $(this).nextAll('.two:first').toggle(); 
});

http://jsfiddle.net/DerekL/5ossufmj/

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
  • Your solution works immediately for this case. But what I am trying to apply it to: I want to get the next element with that `two` class relative to the position of the element I clicked. When I apply your answer, It always returns the first element with class of `two`, ignoring the position of the element I clicked. Does that make sense? – Neil Jul 08 '15 at 23:54
  • 1
    @Neil By "position" do you mean the position in your code or its actual position on the screen? – Derek 朕會功夫 Jul 08 '15 at 23:58
  • The next `` element with the class of `two` relative to the element I clicked. I'm not sure what you mean by position of code or screen. I think screen, because I am using bootstrap for responsive design, so screen may change. – Neil Jul 08 '15 at 23:59
  • 1
    @Neil I see. This is probably what you wanted, [demo](http://jsfiddle.net/DerekL/5ossufmj/). – Derek 朕會功夫 Jul 09 '15 at 00:02
0

I think you might want .next(). It finds the next sibling in the DOM respecting placement in the DOM.

https://api.jquery.com/next/

Or maybe this: get the next element with a specific class after a specific element

Edit

Here is a working solution:

$('.one').on('click', function () {
    var this_el = $(this);
    var el = findNextWithClass(this_el, "two");
    if (el != null)
    {
        el.toggle();
    }
    else
    {
        alert("null");
    }
});

function findNextWithClass(element, className) {
    var next = element.next();
    if (next.hasClass(className)) {
        return next
    } else {
        if (next != null) {
            return findNextWithClass(next, className);
        } else {
            return null;
        }
    }
}
Community
  • 1
  • 1
abalter
  • 9,663
  • 17
  • 90
  • 145