Skip to content Skip to sidebar Skip to footer

Get Parent Id Of This Div

I am looking to find the parent div id (i.e. 'Bakerloo') from this layout when the button is clicked within '.buttonleft0' in jquery / javascript.

Solution 1:

$(this).closest('div').attr('id')

I think this is what you want

Solution 2:

The parent() function returns the jQuery object, so you need to use the attr() for any of it's attributes like so:

$(this).closest().attr('id');

Edit: On further inspection it appears the button isn't the direct child of the div, and so use of the closest() function would be required.

Solution 3:

Straight up Javascript always works for me.

<divid='Bakerloo'class='box'>
    bakerloo<p></p><spanclass='buttons'><spanclass='buttonleft0'><buttononClick='alert(this.parentNode.parentNode.id)'><spanclass='icon icon10'></span></button></span><spanclass='buttonleft'></span><spanclass='buttonright'></span></span><divclass='comingup'></div><divclass='more'></div></div>

Solution 4:

Try this:

$(this).parent().attr("id");

Solution 5:

Your code itself have few errors so here is the correct one:

HTML

<divid='Bakerloo'class='box'>bakerloo<p></p><spanclass='buttons'><spanclass='buttonleft0'><button><spanclass='icon icon10'>Click here</span></button></span><spanclass='buttonleft'></span><spanclass='buttonright'></span></span><divclass='comingup'></div><divclass='more'></div></div>

JQuery

jQuery(document).ready(function($){
    $("button").on('click',function(){
       alert($(this).closest('div').attr('id'));
    });
});

here is the fiddle http://jsfiddle.net/cpeeyush/ydk4e/

Post a Comment for "Get Parent Id Of This Div"