简体   繁体   中英

how to get en id of clicked element jquery

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.

$("#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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM