Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
-2
rated 0 times [  2] [ 4]  / answers: 1 / hits: 29015  / 13 Years ago, mon, august 15, 2011, 12:00:00

Here's some HTML:



<div class=results>
<div id=1>something</div>
<div id=2>something else</div>
<div id=3>blah blah blah</div>
<div id=4>etc</div>
</div>


Now if I can call this using jQuery:



var div = $(.results > div);
div.click(function()
{
alert(this.childNodes[0].nodeValue);
});


When clicking on a div, it will call an alert box saying whats in the div (from the list above: one of 'something', 'something else', 'blah blah blah' or 'etc'). Does anyone know how I can get it to alert the id (in this example, 1, 2, 3 or 4) of the div rather than the information within the node?



Thanks


More From » jquery

 Answers
22

Inside the event handler, this refers to the clicked div. You can access its id property [MDN]:



alert(this.id);


Note: HTML4 does not allow ids to start with digits.



P.S: The selector should be $(.results > div). (fixed)


[#90594] Sunday, August 14, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
clarkulisesa

Total Points: 422
Total Questions: 93
Total Answers: 112

Location: Austria
Member since Thu, Jan 7, 2021
3 Years ago
clarkulisesa questions
Mon, Feb 24, 20, 00:00, 4 Years ago
Mon, Aug 12, 19, 00:00, 5 Years ago
;