Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get original selector using jQuery's on() function with a filter?

Tags:

jquery

I'm using jQuery's .on() function to attach some behavior on the click event on an object, say a span.

My setup looks something like this:

$('#container').on('click', 'span', function() {
    // do stuff
});

Inside this function, this is span. How do I get #container?


Full example: http://jsfiddle.net/aymansafadi/Nk3p9/

<div id="container">
    <span>Click Me!</span>
</div>​

--

$('#container').on('click', 'span', function() {

    var span = $(this),
        div  = false; // This is what I need

    console.log(span);
});​
like image 218
Ayman Safadi Avatar asked Aug 28 '12 23:08

Ayman Safadi


People also ask

How do you select the first element with the selector statement?

The :first selector selects the first element. Note: This selector can only select one single element. Use the :first-child selector to select more than one element (one for each parent). This is mostly used together with another selector to select the first element in a group (like in the example above).

Which method allows you to filter elements based on specified criteria?

jQuery filter() Method The filter() method returns elements that match a certain criteria. This method lets you specify a criteria.

What is the main difference between selectors and filters?

jQuery selector selects all elements based on the elements name given by you. jQuery filter( ) adds further detail to the selected elements by specifying the criteria of selection.

Which type of parameter can jQuery filter function take?

The jQuery filter() method can take the selector or a function as its argument to filters the set of matched elements based on a specific criteria.


1 Answers

Use event.delegateTarget

$('#container').on('click', 'span', function(e) {

    var span = $(this),
    div  = e.delegateTarget;

    console.log(div);
});

DEMO

like image 125
Musa Avatar answered Nov 13 '22 19:11

Musa