How to handle delegated event only for children?

When delegating events using .on how to configure target child elements:

I tried: childSelector =

  • >*
  • >:nth-child(n)

But nothing gets selected when I start with > .

 $(selector).on(event, childSelector, handler); 

Sometimes I want to target a direct child, sometimes I don’t do this: (pseudocode)

 var func = function(selector, subSelector) { $(selector).on("click", subSelector, function() { alert("my subSelector is clicked"); }); } func("#wrapper", "direct-child-selector"); func("#wrapper", ".some .other > .selector:first"); 

That's why I ask for a selector, not a fix.

+8
javascript jquery events delegates children
source share
4 answers

You can check inside the handler whether the element is a child of the element to which the event handler has been delegated;

 $(selector).on("event", '*', function (e) { if (e.target.parentNode === e.delegateTarget) { // Woo! } }); 

See e.delegateTarget . It is worth noting that e.delegateTarget was introduced in jQuery 1.7, so it will not work in older versions.

As for your second edit , in it the current form of the selector is ambiguous; you cannot determine in the code and in its current form whether the selector is passed, only the selector is only for children. You can enter another parameter to indicate whether it was intended only for the child selector or add > to the beginning of the selector (for example) and check it;

 var func = function(selector, subSelector, isChild) { $(selector).on("click", subSelector, function(e) { if (isChild && e.parentNode == e.delegateTarget || !isChild) { alert("my subSelector is clicked"); } }); } func("#wrapper", "direct-child-selector", true); func("#wrapper", ".some .other > .selector:first" /* , `false` is optional */); 

Or:

 var func = function(selector, subSelector) { if (subSelector.charAt(0) === '>') { subSelector = selector + subSelector; } $(selector).on("click", subSelector, function(e) { alert("my subSelector is clicked"); }); } func("#wrapper", "> direct-child-selector"); func("#wrapper", ".some .other > .selector:first"); 
+4
source share

One way to only delegate events triggered on direct children is to provide a full on() selector, including the part that matches the parent element:

 $(selector).on("event", selector + " > *", handler); 
+1
source share

It worked for me.

 $('#container').on('click', '> .children', function(){ ... }) 
+1
source share

All you need is:

 childSelector = "*"; 

if it must match any child of the selector. It only searches in the selector area.

0
source share

All Articles