ajsie
ajsie

Reputation: 79826

all children selector in jquery?

simplified, i've got following code:

 <a id="123" href="#"><span>click</span><span>me</span></a>

when i click on 'click' and 'me' it doesnt seem to work with following jquery selector:

 $("a").click...

maybe its because i click on the children? how could i write the selector so it maps to all children in 'a'?

Upvotes: 0

Views: 3099

Answers (3)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196276

[updated]
The problem is that you are using the wrong tool for the job (namely the event.target property). This will return the element that the event happened on.. but not the element in the bubbling phase that handles the event... you need to use the event.currentTarget.. But in jQuery's case this is also the same as the this keyword inside the handler ...
ref: http://api.jquery.com/event.currentTarget/

Have a read at the Event order as explained at quirksmode. Special attention to Use of event bubbling and currentTarget


[previous answer]
Make sure that inside the .click method you use a function pointer or an anonymous function ..

so

$("a").click( function() {/*...*/} ); // anonymous function

or

function some_function()
{
//...
}
$("a").click ( some_function ) // function pointer

but not

$("a").click ( some_function() ) // unless some_function returns a function pointer..

Upvotes: 5

Khanzor
Khanzor

Reputation: 5010

If you need to get the id of a parent element then you just do this:

$('a').children().click(function() {
  var parentId = $(this).parent('a').attr('id');
  // Code goes here
});

Upvotes: 2

bobince
bobince

Reputation: 536745

i have to fetch the parent's id. how could i do this? im currently using event.target.id

$(event.target).closest('a').attr('id') would do it.

But there's no need to use event.target: in an event handler function the special this variable will point to the element you added the handler to, rather than the descendant element that was clicked:

$('a').click(function() {
    alert('id= '+this.id)
});

(Or $(this).attr('id') if you want to force jQuery to do some extraneous work.)

PS. Don't use IDs that start with a number. It's invalid and can confuse some browsers.

Upvotes: 2

Related Questions