JQuery delegate selector task

I am trying to delegate the click event to all the first anchor tags of all now and future divs with the class "panel". I did something like this:

$('#panel').delegate('.panels a:first', 'click', function(event) [...] 

but that will not work. It associates an event with only one, the first ".panels". Any clues?

+4
source share
2 answers

I donโ€™t think that you can only do this with a selector, unless it happens that the elements a are not only the first anchor, but also the first child of any type inside the โ€œpanelsโ€ of the div (in this case, you can use :first-child )

You may have to put some logic in the handler to verify that clicking the anchor is the first anchor in the div . Something like that:

 $("#panel").delegate(".panels a", "click", function() { if ($(this).siblings("a").andSelf()[0] === this) { // It the first anchor in its parent } return false; }); 

Living example

This works because siblings and andSelf ensure that the array inside the jQuery object is kept in the order of the document, so check if this element works [0] th.

+3
source

You want to use :first-child :first returns only one element.

What you are doing now is $('.panels a').get(0)

A source:
http://api.jquery.com/first-selector/

+3
source

All Articles