Q:

How to Get the ID of the Element that Fired an Event in jQuery

0

How to Get the ID of the Element that Fired an Event in jQuery

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the event.target Property

You can use the event.target property to get the ID of the element that fired an event in jQuery. This property always refers to the element that triggered the event.

The following example will display the name of the element that was just clicked.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get the DOM Element that Initiated the Event</title>
<style>
    div, p, span{
        padding: 30px;
        display: block;        
        border: 3px solid #999;
    }
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    $(document).click(function(event){
        alert("You've clicked: " + event.target.nodeName + ", id: " + event.target.id);
    });
});
</script>
</head>
<body>
    <div id="myDiv">
        <p id="myP">
            <span id="mySpan">Just click anywhere.</span>
        </p>
    </div>
</body>
</html>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Find the Sum of an Array of Numbers in Java... >>
<< How to Insert an Item into an Array at a Specific ...