Get Parent ID of this DIV

前端 未结 7 1184
野性不改
野性不改 2021-01-21 09:45

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.

相关标签:
7条回答
  • 2021-01-21 10:24
    alert($(this).parent().id);
    

    If you want to be sure to select correct class, try:

    alert($(this).parent('.div').id);
    

    If you have a deeper hierarchy you can use:

    alert($(this).parents('.div:eq(n)').id);
    

    where n is which parent you want to get

    0 讨论(0)
  • 2021-01-21 10:25
    $(this).closest('div').attr('id')
    

    I think this is what you want

    0 讨论(0)
  • 2021-01-21 10:27

    Straight up Javascript always works for me.

    <div id='Bakerloo' class='box'>
        bakerloo<p></p>
        <span class='buttons'>
            <span class='buttonleft0'>
            <button onClick='alert(this.parentNode.parentNode.id)'>
                 <span class='icon icon10'></span>
            </button>
            </span>
            <span class='buttonleft'></span>
            <span class='buttonright'></span>
        </span>
        <div class='comingup'></div>
        <div class='more'></div>
    </div>    
    
    0 讨论(0)
  • 2021-01-21 10:35

    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.

    0 讨论(0)
  • 2021-01-21 10:35

    Try this:

    $(this).parent().attr("id");
    
    0 讨论(0)
  • 2021-01-21 10:45

    Try this:

    $(this).closest('div[id]')

    0 讨论(0)
提交回复
热议问题