javascript - how to get en id of clicked element jquery - Stack Overflow

I want to get an id as a string of a div that was clicked. is it possible to do?HTML<div id="

I want to get an id as a string of a div that was clicked. is it possible to do?

HTML

<div id="test">
    <div class='button' id="a" ><p>Click 1</p></div>
    <div class='button' id="b" ><p>Click 2</p></div>
    <div class='button' id="c" ><p>Click 3</p></div>
    <div class='button' id="d" ><p>Click 4</p></div>
</div>

I can do something like this:

  $("#a").click(function() {
      /* do some action with this div */
  });

But I want to detect the id of just clicked div, because I will have a lot of divs like this, and it doesn't make sense to rewrite the same code over and over again.

I want to get an id as a string of a div that was clicked. is it possible to do?

HTML

<div id="test">
    <div class='button' id="a" ><p>Click 1</p></div>
    <div class='button' id="b" ><p>Click 2</p></div>
    <div class='button' id="c" ><p>Click 3</p></div>
    <div class='button' id="d" ><p>Click 4</p></div>
</div>

I can do something like this:

  $("#a").click(function() {
      /* do some action with this div */
  });

But I want to detect the id of just clicked div, because I will have a lot of divs like this, and it doesn't make sense to rewrite the same code over and over again.

Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Jan 22, 2013 at 21:38 VorVor 35.3k46 gold badges141 silver badges196 bronze badges 2
  • 1 Although your HTML is fine, I think I'd choose another class name for your divs: IMO, 'button' can be confusing. – frenchie Commented Jan 22, 2013 at 21:41
  • 1 Also, I don't think you need to have a <p> tag inside your divs; just put the text directly inside the div. As a general rule, when you have a box inside a box (think of tags as boxes) you can probably simplify the HTML by removing the inner box and apply the css of the inner box to the outter box. – frenchie Commented Jan 22, 2013 at 22:09
Add a ment  | 

3 Answers 3

Reset to default 5
$("#a").click(function() {
    var id = this.id;
});

If you need to set click event for all .button elements, here is the short way:

$(".button").click(function(e) {
    var id = this.id;  // or e.target.id;
});
$("div.button").click(function() {
    console.log(this.id);
});
$(this).attr('id')

will get you the id, But if you want to access the div you can use

$(this).parent('div')

this will only return if the immediate parent is a div, if want to find up you can use

$(this).parents('div')

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745568392a4633532.html

相关推荐

  • javascript - how to get en id of clicked element jquery - Stack Overflow

    I want to get an id as a string of a div that was clicked. is it possible to do?HTML<div id="

    6小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信