How to get the element clicked (for the whole document)?
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);
}
You can find the target element in event.target
:
$(document).click(function(event) {
console.log($(event.target).text());
});
References:
- http://api.jquery.com/event.target/
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);}