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.
If the elements being clicked will have a parent with some characteristic you can use (e.g., a class name or other attribute), then
closestmight 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:
That would work, for instance, if you were looking for clicks on the button in this structure:
…or any other structure where both the button and the “viewCommentsExp” were descendants of “container” (whether siblings or not).