3

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

2 Answers 2

13

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)

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! That was it! :) Yes, I know about the selector, that was a typo! Thanks though!
@ing0: Well, one never knows ;) You're welcome, happy coding!
Yea sorry, I didn't mean it like that. Thanks for pointing it out!
2

Alert the id property of the div:

alert(this.id);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.