CoreDo
CoreDo

Reputation: 2891

Get the id of the clicked-upon div

I want to select the id of the current div when I click on it in jQuery.
For example, say I have HTML like this:

<div class="item"  id="10">hello world</div>
<div class="item_10">hello people</div>

When I click on the first div on .item class, I want to copy the id of the current div + adding to it the number (10), so it will be ("div id" + 10) equal to the second dev class = item_10.

I tried to use currentid = this.id; but it doesnt work :( !

Upvotes: 3

Views: 23558

Answers (5)

Phrogz
Phrogz

Reputation: 303168

First, note that id attributes starting with numbers are syntactically illegal in HTML4. If you're using id="10" make sure that you're using the HTML5 doctype (<!DOCTYPE html>).

It's hard to say why what you were doing didn't work without seeing your actual code. Presumably it is because you were registering for the event on a higher element (like the body) and this.id was the id of that higher element and not the element you clicked on.

In this case, you want to use the target property of the event to find what you clicked on. For example:

$(document.body).click(function(evt){
  var clicked = evt.target;
  var currentID = clicked.id || "No ID!";
  $(clicked).html(currentID);
})

Seen in action: http://jsfiddle.net/Gra2P/

If you were registering on the specific elements instead, then this.id does work:

$('div').click(function(evt){
  var currentID = this.id || "No ID!";
  $(this).html(currentID);
})

Seen in action: http://jsfiddle.net/Gra2P/1/

This is sub-ideal, however, because:

  1. It makes many event handler registrations instead of 1, and
  2. If additional divs are added to the document after this code is run, they will not be processed.

Under jQuery 1.7, you use the .on method to create a single event handler on a parent element with selectors for the kinds of elements you want to catch the event on, and have this set to them. In code:

$(document.body).on('click','div',function(evt){
  var currentID = this.id || "No ID!";
  $(this).html(currentID);
})

Seen in action: http://jsfiddle.net/Gra2P/2/

Upvotes: 10

Jayendra
Jayendra

Reputation: 52769

You can simply use this.id

$('div').click(function() {
    var divid = this.id;
    alert($('.item_'+divid).html());
});

Demo

Upvotes: 2

Niels
Niels

Reputation: 49919

I think you're trying to do something like:

$(".item").click(function(){
    var id = $(this).attr("id");
    var el = $(".item_" + id);
});

Now el is your second div.

Upvotes: 2

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

This can be done as:

$('.item').click(function() {
var divId = $(this).attr("id");

});

Upvotes: 0

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174957

Something like this?:

$('div').click(function() {
    theId = $(this).attr('id');
    //Do whatever you want with theId.
});

Upvotes: 1

Related Questions