Nitish T
Nitish T

Reputation: 162

Select the id of an element using jquery

Following are the divs i have:

<div class="grey-column" id="infoblock1" data-type="datahere"></div>
<div class="green-column" id="infoblock2" data-type="datahere"></div>
<div class="red-column" id="infoblock3" data-type="datahere"></div>

I am trying to find out the id of the element which has been clicked, I have this code:

$(function(){
    $('.green-column, .red-column, .grey-column').click(function() { 
         id_clicked = this.id; 
         var id_final = '#';
         id_final += id_clicked;
         $("<div>" + $(id_final).attr("data-type") + "</div>").dialog();
    });
});

So whenever a user clicks a div, the click function will be fired, and the id of the element clicked is found. But the attr() function doesn't seem to be working here. Please help me out.

Upvotes: 0

Views: 77

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074295

Since this is the DOM element clicked, you don't need to go indirectly through the id to get at its attributes. Just:

$(function(){
    $('.green-column, .red-column, .grey-column').click(function() { 
         $("<div>" + $(this).attr("data-type") + "</div>").dialog();
    });
});

Example Fiddle

But as your code does work provided you're not in strict mode (barring the fact that it falls prey to The Horror of Implicit Globals by not declaring the id_clicked variable), you'll want to look at the JavaScript console and such to find out what else is going on that's preventing it from working correctly.

Upvotes: 2

Dead Man
Dead Man

Reputation: 2921

Try this :

$(function(){
    $("div").click(function(){
        var div_id = $(this).attr("id");
        $("<div>" + $("#"+div_id).attr("data-type") + "</div>").dialog();
    });
});

Demo : http://jsfiddle.net/7gxeY/1/

Upvotes: 0

Anujith
Anujith

Reputation: 9370

Try:

$(function(){
 $('.green-column, .red-column, .grey-column').click(function() { 
     $("<div>" + $(this).data("type") + "</div>").dialog();
 });
});

To get the clicked element use $(this) and to get data-type value use .data()

Upvotes: 0

Related Questions