Reputation: 13
<div id="maindiv">
<DIV id="first">first div<DIV>
<DIV id="second">second div</DIV>
<input id="input" type="text"/>
<button id="button" value="send"></button>
</div>
I want to get the id of the div inside the main div when one of the inner div is clicked using jquery. How can this be done?
Upvotes: 1
Views: 124
Reputation: 4527
$('#main_div').children().click(function() {
alert(this.id);
});
Note that "children()" optionally takes a selector, so you could specify which children will have the click event, e.g. the following will make sure that only elements with an id will work:
$('#main_div').children('[id]').click(function() {
alert(this.id);
});
Upvotes: 0
Reputation: 93003
$('#maindiv div').on('click', function(e) { // or '#maindiv > div' for proper children
e.stopPropagation(); // or else this will bubble up through the DOM
var my_id = $(this).attr('id');
alert(my_id);
});
Upvotes: 1
Reputation: 12998
var the_id;
$("#main_div > div").click( function() {
the_id = $(this).attr("id);
}
Note that id's can not contain spaces.
Upvotes: 0