is there any way to use a jQuery selector in a delegated event with .on() ?
And how would you select only immediate children in the selector ?
Below is a sample of code : I’d like to filter only immediate <div> children of the <section> element, with the requirement that at least one of their <p> children contains the word «hello».
In the example, only the second <div> would be filtered. The problem is that other <div> can be added afterwards, so the event must be delegated.
The use of the .live() method made it more simple imho, as I could have used :
$('section > div').filter(function(){return /hello/.test(p) }).live('mouseenter', function(){ ... })
But as it’s deprecated now, its replacement .on() only allows pure CSS-like selectors in delegated events.
Has anyone got any idea on how to filter these elements based on the 2 aforementioned conditions (immediate children & <p> contain hello) ?
Thanks
<section>
<div>
<p>abc</p>
<div>
<p>def</p>
<p>hello</p>
</div>
</div>
<div>
<p>hello world</p>
<p>test</p>
</div>
</section>
EDIT : I forgot to add my JS sample, and I’m modifying the condition a little bit so that p:contains(‘hello’) does not suffice as a selector.
$('section').on({
mouseenter: function(){
$(this).css('background-color','red');
}
},
$('div').filter(function(){
var p = $(this).children('p').filter(function(){
return /hello/.test($(this).text());
});
return p.length > 2;
})
);
to have the event on the div, you’ll have to set the condition inside the function
It was laziness as i always do it in my code : it’s better to attach event to document and delegate; jquery works way way faster that way + you can add element dynamically without worrying of whether event will be triggered or not (it will)