Ticket #4101 (closed feature: fixed)
add public contains method
| Reported by: | joern | Owned by: | yehuda |
|---|---|---|---|
| Priority: | major | Milestone: | 1.4 |
| Component: | core | Version: | 1.4a1 |
| Keywords: | Cc: | ||
| Blocking: | Blocked by: |
Description (last modified by joern) (diff)
Both Sizzle and jQuery UI core have their own internal contains-method. This could/should be added to the public API, maybe as a filter-variant:
$(".container").contains(event.target).doSomething();
To accept the most variant of arguments, a double-filter would be necessary:
// already exists in Sizzle
var contains = document.compareDocumentPosition ? function(a, b){
return a.compareDocumentPosition(b) & 16;
} : function(a, b){
return a !== b && (a.contains ? a.contains(b) : true);
};
$.fn.contains = function(target) {
var targets = $(target);
return this.filter(function() {
var container = this;
return targets.filter(function() {
return container.contains(this);
}).length;
});
}
Probably a rather naiive implementation, but it would ensure that both each of the selected elements and each of the arguments are considered.
The immediate usecase for me is to implement a subform-feature for the validation plugin. When an event like keyup or blur is triggered, I need to check if that target-element is contained inside the active subform-element, if so, validate it, if not, ignore the event. If it isn't inside any subform element, validate it, too. Something like this:
var validator = ...;
$("form").keyup(function(event) {
if (validator.subforms.contains(event.target) && validator.subforms.filter(":active").contains(event.target) {
$(event.target).valid();
}
});
Attachments
Change History
comment:3 Changed 4 years ago by kswedberg
Hi Jörn,
I wonder about the naming of this method. It might cause some confusion, because we have a :contains selector that filters for text, not elements. Since it looks like your .contains() method is functionally similar to the :has selector, would it make more sense to call it .has()?
For example, if I'm understanding correctly, $(".container").contains(event.target) would return the same elements as $(".container:has(" + event.target + ")").
comment:4 Changed 4 years ago by paul.irish
Since :not and :eq have matching method names, I'd agree with Karl on considering this method .has().
comment:6 Changed 4 years ago by joern
As a first step, and to remove the duplication in ui.core.js: Can we just expose the current method as $.contains?
comment:8 Changed 4 years ago by yehuda
- Owner set to yehuda
- Status changed from new to assigned
I have attached a patch against Sizzle and a patch against jQuery that adds .has support. It adds support for all standard parameters (as in filter and not)
Please follow the bug reporting guidlines and use jsFiddle when providing test cases and demonstrations instead of pasting the code in the ticket.

