Pinkie
Pinkie

Reputation: 10246

jQuery selector using on

$('#container').on('click', 'a',function()..

and

$('#container a').on('click',function()..

What is the difference between both selectors.

Upvotes: 2

Views: 60

Answers (5)

Kevin B
Kevin B

Reputation: 95023

The first will bind to all current and future anchor tags while the second will only bind to existing anchor tags.

the first is almost identical to using .delegate(), the only difference is the event and selector are swapped.

Edit: Answer to comment since it is rather long

The first is useful for dynamic content or content that contains a lot of anchor tags. The first only binds a single event that listens for events to bubble up to it that were triggered on elements that match the given selector. The first one could be re-written as $("#container").delegate("a","click",function()... for the exact same functionality. It is far more efficient in most cases than binding events directly to the elements. However, if your content is not dynamic and doesn't contain very many anchor tags, you should use the second piece of code because it is less complex than the first.

Upvotes: 3

scripto
scripto

Reputation: 2297

I guess the 'a' is a selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.

Upvotes: 0

mreq
mreq

Reputation: 6542

Check the jQuery docs

selector
A selector string to filter the descendants of the selected elements that
trigger the event. If the selector is null or omitted, the event is always
triggered when it reaches the selected element.

Upvotes: 0

David Thomas
David Thomas

Reputation: 253308

The former attaches the click-handler to the #container element, which assigns an event if the click happens to be focused on an a element. This is particularly useful if the a elements might be updated, removed or added dynamically following assignment/binding of event-handlers.

The latter attaches the click handler directly to the a elements contained within the #container element. Which means those elements must be present in the DOM at the time the event-handlers and functions are bound to the nodes in the DOM.

Upvotes: 1

Naftali
Naftali

Reputation: 146302

  1. Code snippet 1:

    Set a click event to all anchor tags that are or will be in #container

  2. Code snippet 2:

    Set a click event to all anchor tags in #container

Upvotes: 3

Related Questions