Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $(this).closest show & hide

Tags:

jquery

I've got a table with multiple rows. In each row is a Show Details Button and a Hide Details button. On clicking show details I want the hide details button to only show for the specific row. I thought the .closest() function would work but it hasn't yet.

Here is the HTML

<table>
    <tr id="1">
      <td><button class='view'>View Details</button><button class='hide' style='display:none;'>Hide Details</button></td>
    </tr>

    <tr id="2">
      <td><button class='view'>View Details</button><button class='hide' style='display:none;'>Hide Details</button></td>
    </tr>
</table>

Here is the jQuery

$(".view").click(function() {   
    $("#patient").show("");
    $(this).hide();
    $(this).closest(".hide").show();
});
like image 604
Chris Olson Avatar asked Aug 02 '13 19:08

Chris Olson


People also ask

How can I find previous siblings in jQuery?

jQuery prev() Method The prev() method returns the previous sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse backwards along the previous sibling of DOM elements.

How do I get the closest div using jQuery?

The closest() is an inbuilt method in jQuery that returns the first ancestor of the selected element in the DOM tree. This method traverse upwards from the current element in the search of first ancestor of the element.

How do I find a specific parent in jQuery?

jQuery parent() Method The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree.

What does closest mean in jQuery?

The closest() method returns the first ancestor of the selected element. An ancestor is a parent, grandparent, great-grandparent, and so on. The DOM tree: This method traverse upwards from the current element, all the way up to the document's root element (<html>), to find the first ancestor of DOM elements.


2 Answers

.closest looks at the current element and its parents only. You'd have to do this like:

$(this).parent().find('.hide');

or

$(this).siblings('.hide');
like image 125
kalley Avatar answered Sep 18 '22 14:09

kalley


Are you binding after the dom is ready? Try this:

$(function(){
    $(".view").click(function() {   
        $("#patient").show("");
        $(this).hide().next().show();
    });
});
like image 36
Prasanth Avatar answered Sep 19 '22 14:09

Prasanth