Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .closest() returns multiple results within a custom jQuery plugin

Tags:

jquery

closest

While hacking my free-time project I stumbled upon a puzzling jQuery behaviour.

I have a custom validation plugin written and working. In the plugin I wanted to implement some functionality using .closest() method. Strangely enough this method returns multiple elements.

Here is a sample code:

this.closest(".control-group")
$(this).closest(".control-group");

Both above code lines select all four elements with class "control-group". This code put inside my plugin works:

var element_ID = this.attr("id");
$("#" + element_ID).closest(".control-group")

Above selects the correct and only one element with "control-group" class.

I can't use this "hack" as not all elements that I want to validate have "id" property set, so it won't work in all cases.

Using jQuery 1.7.2 (seems to be latest stable). Any ideas why it's like that?

like image 992
koniczynek Avatar asked Jun 14 '12 09:06

koniczynek


2 Answers

this is a jQuery object that contains at least 4 DOM elements, and calling .closest on it will retrieve the closest .control-group elements for all of those.

this.attr("id") will retrieve the id of the first dom element in the jQuery object, so you could have just done $(this[0]).closest...

like image 50
Esailija Avatar answered Oct 27 '22 02:10

Esailija


you may not have id's for all the elements but you do have this

instead of

var element_ID = this.attr("id");
$("#" + element_ID).closest(".control-group")

try

$(this).closest(".control-group")

Update

The jQuery site says:

Given a jQuery object that represents a set of DOM elements, the .closest() method searches through these elements and their ancestors in the DOM tree and constructs a new jQuery object from the matching elements. The .parents() and .closest() methods are similar in that they both traverse up the DOM tree. The differences between the two, though subtle, are significant:

.closest() : The returned jQuery object contains zero or one element

.parents() : The returned jQuery object contains zero, one, or multiple elements

here is the link: http://api.jquery.com/closest/

So your original question is maybe not answered

like image 25
U.P Avatar answered Oct 27 '22 02:10

U.P