Another way to get the element we clicked on in the event handler is to get it from the event object which is the first parameter in the event handler function. And the following JavaScript code: const onClick = (event) => { console. log(event.srcElement.id); } window.
Answer: Use the target Property You can simply use the event. target property to get the class from any element which is clicked on the document in jQuery.
The * selector selects all elements. The * selector can also select all elements inside another element (See "More Examples").
We can bind a JavaScript function to a div using the onclick event handler in the HTML or attaching the event handler in JavaScript. Let us refer to the following code in which we attach the event handler to a div element. The div element does not accept any click events by default.
You need to use the event.target
which is the element which originally triggered the event. The this
in your example code refers to document
.
In jQuery, that's...
$(document).click(function(event) {
var text = $(event.target).text();
});
Without jQuery...
document.addEventListener('click', function(e) {
e = e || window.event;
var target = e.target || e.srcElement,
text = target.textContent || target.innerText;
}, false);
Also, ensure if you need to support < IE9 that you use attachEvent()
instead of addEventListener()
.
event.target
to get the element
window.onclick = e => {
console.log(e.target); // to get the element
console.log(e.target.tagName); // to get the element tag name alone
}
to get the text from clicked element
window.onclick = e => {
console.log(e.target.innerText);
}
use the following inside the body tag
<body onclick="theFunction(event)">
then use in javascript the following function to get the ID
<script>
function theFunction(e)
{ alert(e.target.id);}
You can find the target element in event.target
:
$(document).click(function(event) {
console.log($(event.target).text());
});
References:
Use delegate
and event.target
. delegate
takes advantage of the event bubbling by letting one element listen for, and handle, events on child elements. target
is the jQ-normalized property of the event
object representing the object from which the event originated.
$(document).delegate('*', 'click', function (event) {
// event.target is the element
// $(event.target).text() gets its text
});
Demo: http://jsfiddle.net/xXTbP/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With