jquerybuttonjquery-selectorssiblingsclosest

How to target elements in another element using jQuery


I want to target certain <button>'s in an element specific container on webpage.

Here is my situation:

I am trying to .show() button's B4 and B5 by clicking button "B3".

Here is my markup:

<tr>
  <td class="leftSide">
    <button class="b1" style="display:inline">B1</button>
    <button class="b2" style="display:inline">B2</button>
    <button class="b3" style="display:inline">B3</button>
  </td>
  <td>Some middle-ground content</td>
  <td class="rightSide">
    <button class="b4" style="display:none">B4</button>
    <button class="b5" style="display:none">B5</button>
  </td>
</tr>

Here is my jQuery:

  $( '.b3' ).click(function() {
    $(this).hide();
    $(this).siblings('.b4').show(); // tried this and it does not work
    $(this).siblings('.b5').show(); // tried this and it does not work
    $(this).nearest('.b4').show(); // tried this but it throws an error
    $(this).nearest('.b5').show(); // tried this but it throws an error
    $(this).closest('.b4').show(); // tried this and it does not work
    $(this).closest('.b5').show(); // tried this and it does not work
    $(this).next('.b4').show(); // tried this and it does not work
    $(this).next('.b5').show(); // tried this and it does not work
    $(this).parent().find(".rightSide .b4").show(); // tried this and it does not work
    $(this).parent().find(".rightSide .b5").show(); // tried this and it does not work
});

Is it possible to reach the buttons in the rightSide container?


Solution

  • Hi you can try this way

    $(function() {
       $('table .b3').on('click', function(){
        
        // $(this).parent().nextUntil('rightSide').next().show();
        // $(this).parent().find(".rightSide").next().show();
        // $(this).next('td').next('td').find('.b4').show();
        $(this).parent().next('td').next('td').find('.b4, .b5').show();
       })
    });	
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table>
    <tr>
      <td class="leftSide">
        <button class="b1" style="display:inline">B1</button>
        <button class="b2" style="display:inline">B2</button>
        <button class="b3" style="display:inline">B3</button>
      </td>
      <td>Some middle-ground content</td>
      <td class="rightSide">
        <button class="b4" style="display:none;">B4</button>
        <button class="b5" style="display:none;">B5</button>
      </td>
    </tr>
    <tr>
      <td class="leftSide">
        <button class="b1" style="display:inline">B1</button>
        <button class="b2" style="display:inline">B2</button>
        <button class="b3" style="display:inline">B3</button>
      </td>
      <td>Some middle-ground content</td>
      <td class="rightSide">
        <button class="b4" style="display:none;">B4</button>
        <button class="b5" style="display:none;">B5</button>
      </td>
    </tr>
    </table>