Atnaize
Atnaize

Reputation: 1816

JQuery selector on click event

I want to trigger something when I click on a certain class within a div.

I tried this

$("div .event").click(function() {
    alert($( this ).text());
}); 

And

$("div").on("click", $('.event'), function() {
    alert($( this ).text());        
}); 

//Or 
$(".SimpleCalendar .event").click(function() {
    alert($( this ).text());
}); 
//I do not even know what this is supposed to do ...
$(".SimpleCalendar tbody tr td div .event").click(function() {
    alert($( this ).text());
}); 

And many more but still can not figure out why this is not working

My HTML is the following : enter image description here

Upvotes: 0

Views: 57

Answers (2)

Sachin
Sachin

Reputation: 978

You were making use of parent descendent selector, since event class is on the div itself and not its descendent your selector was incorrect.

One of these should work for you

Try this

$("div.event").click(function() {
    alert($( this ).text());
});

or,

$(".SimpleCalendar").on("click", '.event', function() {
    alert($( this ).text());        
}); 

For more information on choosing right selectors please see this

Upvotes: 1

PeterKA
PeterKA

Reputation: 24638

The div that you're selecting is the one that has the class .event, not a descendant of it. Therefore the correct selector is div.event. Try this:

$("div.event").click(function() {
    alert($( this ).text());
});

Or just:

//Warning: if elements unlike the div also have the event class then stick to 
//the above as the selector is more specific
$(".event").click(function() {
    alert($( this ).text());
}); 

And don't forget that each of these options should be in DOM ready like so:

$(function() {
    $("div.event").click(function() {
        alert($( this ).text());
    }); 
});

Upvotes: 1

Related Questions