开发者

Get div id using javascript

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 d开发者_开发百科iv (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


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)


Alert the id property of the div:

alert(this.id);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜