'Implementing jQuery "closest"

I am using this jQuery function to find the parent element with class name "viewCommentsExp".

 $('.viewCommentsExpBtn').click(function(e){
    e.preventDefault();

var trackid= $(this).parent().find(".trackidField2").val();
var parent = $(this).parent().parent().parent().find(".viewCommentsExp");

        $.ajax({
            type: "POST",
            data: "trackid="+trackid,
            url: "http://rt.ja.com/viewcomments.php",
            success: function(data)
            {   
             $(".newUserComment").html(data);
            $(parent).slideToggle();

                }
            });
     });

I have this function working on about 90% of the clicks. But, randomly, sometimes all divs with this classname are selected rather than the closest.

Can I clean this up to work more reliably using jQuery "closest"?

$(this).parent().parent().parent().find(".viewCommentsExp");

Not sure how to implement this.



Solution 1:[1]

If the elements being clicked will have a parent with some characteristic you can use (e.g., a class name or other attribute), then closest might be helpful. It depends on your HTML structure, which you haven't shown (as of this writing, I'm guessing you'll probably add it, but I have to disappear).

For instance, if the elements will be in something with the class "container", and the "viewCommentsExp" is a descendant of that "container" element, then:

var viewCommentsExp = $(this).closest(".container").find(".viewCommentsExp");

That would work, for instance, if you were looking for clicks on the button in this structure:

<div class="container">
<input type="button">
<span class="viewCommentsExp">...</span>
</div>

...or any other structure where both the button and the "viewCommentsExp" were descendants of "container" (whether siblings or not).

Solution 2:[2]

You should use the jQuery function closest().

var parent = $(this).closest('.viewCommentsExp');

Since the function closest returns a jQuery object, no need to wrap it again.

parent.slideToggle();

Solution 3:[3]

I think it should be:

var parent = $(this).closest('.viewCommentsExp');

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 T.J. Crowder
Solution 2 guzart
Solution 3 AK Asraful Zaid