ChatGPT解决这个技术问题 Extra ChatGPT

Getting the ID of the element that fired an event

Is there any way to get the ID of the element that fires an event?

I'm thinking something like:

$(document).ready(function() { $("a").click(function() { var test = caller.id; alert(test.val()); }); });

Except of course that the var test should contain the id "aaa", if the event is fired from the first form, and "bbb", if the event is fired from the second form.

Your example is a bit odd. You're attaching a click event to 'a', but don't have any anchors. Changing it to $('input.title').click(...) would be a little clearer for future readers of your question.
You can use event.target.id in event handler to get id of element that fired an event.
You can take event as an argument in you click callback function and then use event.target.id

J
Jack Bashford

In jQuery event.target always refers to the element that triggered the event, where event is the parameter passed to the function. http://api.jquery.com/category/events/event-object/

$(document).ready(function() {
    $("a").click(function(event) {
        alert(event.target.id);
    });
});

Note also that this will also work, but that it is not a jQuery object, so if you wish to use a jQuery function on it then you must refer to it as $(this), e.g.:

$(document).ready(function() {
    $("a").click(function(event) {
        // this.append wouldn't work
        $(this).append(" Clicked");
    });
});

Wow! Thanks. Didn't realize that jQuery abstracted that so well. You rock! I would think it would still have the difference between (this) and (event.target) -- being object you bound the event to vs. the object that received the event.
Unfortunately, event.target doesn't permit access to its custom attributes. To do that, one must use $(this).attr("organization:thingy");.
@ZianChoy - I'm not quite sure what you mean by "custom attributes", but you can use $(event.target) if you need a jQuery method, e.g., $(event.target).attr("organisation:thingy");.
Please note, that: event.target is the real item being clicked. If you, for example, you bind a click event to a div, and, inside that div is a P and an H2 element - event.target will return the H2 element or the P, if clicked one of those. "this" will really return the div on which you hung the event, regardless of what child element you clicked.
I use event.currentTarget.id , event.target.id could also be a child element
P
Peter Mortensen

For reference, try this! It works!

jQuery("classNameofDiv").click(function() {
    var contentPanelId = jQuery(this).attr("id");
    alert(contentPanelId);
});

@gemma The other solution did not work for me but this one did. Thanks for being late.
@dlackey it's the same for me, the other solution did not work on my firefox 12, but this one did. Thanks
The top answer doesn't seem to work for getting the ID of an element in an embedded SVG. $(this).attr("id"); does.
Keep in mind that if your click event is on an element with children, e.target will give you the exact element that caused the event to be fired even if it was a child, whereas this will give you the element that the event is attached to.
d
dun

Though it is mentioned in other posts, I wanted to spell this out:

$(event.target).id is undefined

$(event.target)[0].id gives the id attribute.

event.target.id also gives the id attribute.

this.id gives the id attribute.

and

$(this).id is undefined.

The differences, of course, is between jQuery objects and DOM objects. "id" is a DOM property so you have to be on the DOM element object to use it.

(It tripped me up, so it probably tripped up someone else)


to me, event.target.id gives nothing!
@artaxerxe this means your clicked element doesn't have an id :P; also don't use jquery for this kind of things.... use event javascript attributes instead cause it's faster.
$(event.target).attr('selector'); worked perfectly for me.
A
Alexander Elgin

For all events, not limited to just jQuery you can use

var target = event.target || event.srcElement;
var id = target.id

Where event.target fails it falls back on event.srcElement for IE. To clarify the above code does not require jQuery but also works with jQuery.


Not using jQuery means less lines of code are run while getting the exact same result, as shown above. jQuery abstracts away js. This is the direct js answer, and look at the size!
isn't it better to just use 'this' keyword which is always gonna give you access to properties of the element that invoked the event?
Just had to dig through the all the jQuery crap to get to this answer. Thanks. This is more relevant than ever: needsmorejquery.com
s
sr01853

You can use (this) to reference the object that fired the function.

'this' is a DOM element when you are inside of a callback function (in the context of jQuery), for example, being called by the click, each, bind, etc. methods.

Here is where you can learn more: http://remysharp.com/2007/04/12/jquerys-this-demystified/


if you have a function like $(html).click() (this) will return the html object and not the clicked element
A
Alexander Elgin

I generate a table dynamically out a database, receive the data in JSON and put it into a table. Every table row got a unique ID, which is needed for further actions, so, if the DOM is altered you need a different approach:

$("table").delegate("tr", "click", function() {
   var id=$(this).attr('id');
   alert("ID:"+id);  
});

Oh yeah, this is what I was looking for. It also works the same for the newer "on" since "delegate" is now deprecated. I had checkboxes created dynamically from DB data, and of course they all had different IDs which I needed to use to do something when clicked. I used this method here to get which ID was actually clicked. In old school JS I just passed the id from each checkbox in the checkbox's HTML, but can't do it that way with the jQuery event handler model.
M
Maciej Sikora

Element which fired event we have in event property

event.currentTarget

We get DOM node object on which was set event handler.

Most nested node which started bubbling process we have in

event.target

Event object is always first attribute of event handler, example:

document.querySelector("someSelector").addEventListener(function(event){

 console.log(event.target);
 console.log(event.currentTarget);

});

More about event delegation You can read in http://maciejsikora.com/standard-events-vs-event-delegation/


C
Cerbrus

The source element as a jQuery object should be obtained via

var $el = $(event.target);

This gets you the source of the click, rather than the element that the click function was assigned too. Can be useful when the click event is on a parent object EG.a click event on a table row, and you need the cell that was clicked

$("tr").click(function(event){
    var $td = $(event.target);
});

C
Cris

this works with most types of elements:

$('selector').on('click',function(e){
    log(e.currentTarget.id);
    });

D
Darius

You can try to use:

$('*').live('click', function() {
 console.log(this.id);
 return false;
});

B
Basant Rules

Use can Use .on event

  $("table").on("tr", "click", function() {
                    var id=$(this).attr('id');
                    alert("ID:"+id);  
                });

I
Isochronous

In the case of delegated event handlers, where you might have something like this:

<ul>
    <li data-id="1">
        <span>Item 1</span>
    </li>
    <li data-id="2">
        <span>Item 2</span>
    </li>
    <li data-id="3">
        <span>Item 3</span>
    </li>
    <li data-id="4">
        <span>Item 4</span>
    </li>
    <li data-id="5">
        <span>Item 5</span>
    </li>
</ul>

and your JS code like so:

$(document).ready(function() {
    $('ul').on('click li', function(event) {
        var $target = $(event.target),
            itemId = $target.data('id');

        //do something with itemId
    });
});

You'll more than likely find that itemId is undefined, as the content of the LI is wrapped in a <span>, which means the <span> will probably be the event target. You can get around this with a small check, like so:

$(document).ready(function() {
    $('ul').on('click li', function(event) {
        var $target = $(event.target).is('li') ? $(event.target) : $(event.target).closest('li'),
            itemId = $target.data('id');

        //do something with itemId
    });
});

Or, if you prefer to maximize readability (and also avoid unnecessary repetition of jQuery wrapping calls):

$(document).ready(function() {
    $('ul').on('click li', function(event) {
        var $target = $(event.target),
            itemId;

        $target = $target.is('li') ? $target : $target.closest('li');
        itemId = $target.data('id');

        //do something with itemId
    });
});

When using event delegation, the .is() method is invaluable for verifying that your event target (among other things) is actually what you need it to be. Use .closest(selector) to search up the DOM tree, and use .find(selector) (generally coupled with .first(), as in .find(selector).first()) to search down it. You don't need to use .first() when using .closest(), as it only returns the first matching ancestor element, while .find() returns all matching descendants.


Useful! I adjusted in my case because I just got a simple
  • and so I'd used itemId = $target.attr('id').
  • Just be careful about using a simple ID attribute, as every ID needs to be unique on that page. So if you for some reason need to have two lists like that on that page, you'll likely wind up with duplicate IDs, which is a bad thing. That's why I tend to always use data-id just for future-proofing.
    A
    Alexander Elgin

    This works on a higher z-index than the event parameter mentioned in above answers:

    $("#mydiv li").click(function(){
    
        ClickedElement = this.id;
        alert(ClickedElement);
    });
    

    This way you will always get the id of the (in this example li) element. Also when clicked on a child element of the parent..


    h
    honk
    var buttons = document.getElementsByTagName('button');
    var buttonsLength = buttons.length;
    for (var i = 0; i < buttonsLength; i++){
        buttons[i].addEventListener('click', clickResponse, false);
    };
    function clickResponse(){
        // do something based on button selection here...
        alert(this.id);
    }
    

    Working JSFiddle here.


    I think this is a bit like outdated option to make it work
    @ArnasPečelis outdated? no, just not jQuery.
    E
    Error404

    Just use the this reference

    $(this).attr("id")
    

    or

    $(this).prop("id")
    

    That fetches the attribute id from the element where click() has been assigned on. If you need to transfer more data to that method, you need data-some-id="<?php $someId; ?>" and then you can `$(this).data("some-id") to retrieve it.
    b
    barbsan
    $(".classobj").click(function(e){
        console.log(e.currentTarget.id);
    })
    

    @ManuelMannhardt there's no link in this answer, it's code-only answer, not link-only answer
    A
    Angel Politis

    this.element.attr("id") works fine in IE8.


    M
    Moji

    Both of these work,

    jQuery(this).attr("id");
    

    and

    alert(this.id);
    

    K
    Kamil Kiełczewski

    Pure JS is simpler

    aaa.onclick = handler;
    bbb.onclick = handler;
    
    function handler() { 
      var test = this.id; 
      console.log(test) 
    }
    

    aaa.onclick = handler; bbb.onclick = handler; function handler() { var test = this.id; console.log(test) }


    x
    xeon

    You can use the function to get the id and the value for the changed item(in my example, I've used a Select tag.

                  $('select').change(
                       function() {
                            var val = this.value;
                            var id = jQuery(this).attr("id");
                            console.log("value changed" + String(val)+String(id));
                       }
                   );
    

    D
    DAB

    I'm working with

    jQuery Autocomplete

    I tried looking for an event as described above, but when the request function fires it doesn't seem to be available. I used this.element.attr("id") to get the element's ID instead, and it seems to work fine.


    D
    David Dehghan

    In case of Angular 7.x you can get the native element and its id or properties.

    myClickHandler($event) {
        this.selectedElement = <Element>$event.target;
        console.log(this.selectedElement.id)
        this.selectedElement.classList.remove('some-class');
    }
    

    html:

    <div class="list-item" (click)="myClickHandler($event)">...</div>
    

    v
    vr_driver

    There's plenty of ways to do this and examples already, but if you need take it a further step and need to prevent the enter key on forms, and yet still need it on a multi-line textarea, it gets more complicated. The following will solve the problem.

    <script>
        $(document).ready(function() {
          $(window).keydown(function(event){
            if(event.keyCode == 13) {
               //There are 2 textarea forms that need the enter key to work.
                if((event.target.id=="CommentsForOnAir") || (event.target.id=="CommentsForOnline"))
                {
                    // Prevent the form from triggering, but allowing multi-line to still work.
                }
                else
                {
                    event.preventDefault();
                    return false;
                }         
            }
          });
        });
    </script>
    
    <textarea class="form-control" rows="10" cols="50" id="CommentsForOnline" name="CommentsForOnline" type="text" size="60" maxlength="2000"></textarea>
    

    It could probably be simplified more, but you get the concept.


    Single = in the if?