Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the ID's of div tags

Tags:

jquery

I have the following HTML snippet

<div id="column_1">
    <div id="portlet_1">
        <div id="portlet-header_1"> <input type="button" class="close_button"> </div>
        <div id="portlet-sub-header_1"> sub header goes here </div>
        <div id="portlet-content_1"> content goes here </div>
        <div id="portlet-footer_1"> footer goes here </div>
    </div>
    <div id="portlet_2">
        <div id="portlet-header_2"> <input type="button" class="close_button"> </div>
        <div id="portlet-sub-header_2"> sub header goes here </div>
        <div id="portlet-content_2"> content goes here </div>
        <div id="portlet-footer_2"> footer goes here </div>
    </div>
</div>

<div id="column_2">
    <div id="portlet_3">
        <div id="portlet-header_3"> <input type="button" class="close_button"> </div>
        <div id="portlet-sub-header_3"> sub header goes here </div>
        <div id="portlet-content_3"> content goes here </div>
        <div id="portlet-footer_3"> footer goes here </div>
    </div>
    <div id="portlet_4">
        <div id="portlet-header_4"> <input type="button" class="close_button"> </div>
        <div id="portlet-sub-header_4"> sub header goes here </div>
        <div id="portlet-content_4"> content goes here </div>
        <div id="portlet-footer_4"> footer goes here </div>
    </div>
</div>

How do I:

  1. get the column id depending on which close button is clicked? So if close_button is clicked which is in portlet-header_3, it should return column_2

  2. get the portlet id depending on which close button is clicked? So if close_button is clicked which is in portlet-header_1, it should return portlet_1

I have the following, but this returns the closest div, portlet-header_*, which is not what I am after:

$(".close_button").live('click', function(event) {
    event.preventDefault(); 

    var that = this;
    alert( $(that).closest("div").attr("id") )
});
like image 604
oshirowanen Avatar asked Jul 20 '11 15:07

oshirowanen


1 Answers

Try this (using jQuery .parents()):

$(".close_button").live('click', function(event) {
    event.preventDefault(); 
    var that = this;
    alert( $(that).parents("[id^=column_]").attr("id") )
});

Fiddle: http://jsfiddle.net/maniator/3EJBC/

like image 189
Naftali Avatar answered Sep 25 '22 20:09

Naftali