asad rana
asad rana

Reputation: 13

getting id of elements inside the div

<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

Answers (3)

CompanyDroneFromSector7G
CompanyDroneFromSector7G

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

Blazemonger
Blazemonger

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);
});​

http://jsfiddle.net/Rn9Bu/

Upvotes: 1

Tom
Tom

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

Related Questions