Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the element clicked (for the whole document)?

People also ask

How do you get the click element?

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.

Which property is used to get the clicked element?

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.

How do I select all elements on a page?

The * selector selects all elements. The * selector can also select all elements inside another element (See "More Examples").

Can Div have onClick?

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:

  • http://api.jquery.com/event.target/

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/