Bug Tracker

Opened 13 years ago

Last modified 12 years ago

#4101 closed feature

add public contains method — at Version 1

Reported by: joern Owned by:
Priority: major Milestone: 1.4
Component: core Version: 1.4a1
Keywords: Cc:
Blocked by: Blocking:

Description (last modified by joern)

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();
  }
});

Change History (1)

comment:1 Changed 13 years ago by joern

Description: modified (diff)
Note: See TracTickets for help on using tickets.