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

I would like to get the current element (whatever element that is) in an HTML document that I clicked. I am using:

$(document).click(function () {
    alert($(this).text());
});

But very strangely, I get the text of the whole(!) document, not the clicked element.

How to get only the element I clicked on?

Example

<body>
    <div class="myclass">test</div>
    <p>asdfasfasf</p>
</body>

If I click on the "test" text, I would like to be able to read the attribute with $(this).attr("myclass") in jQuery.

This question is related to javascript jquery html dom

The answer is


I know this post is really old but, to get the contents of an element in reference to its ID, this is what I would do:

window.onclick = e => {
    console.log(e.target);
    console.log(e.target.id, ' -->', e.target.innerHTML);
}

Here's a solution that uses a jQuery selector so you can easily target tags of any class, ID, type etc.

jQuery('div').on('click', function(){
    var node = jQuery(this).get(0);
    var range = document.createRange();
    range.selectNodeContents( node );
    window.getSelection().removeAllRanges();
    window.getSelection().addRange( range );
});

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/


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);}


$(document).click(function (e) {
    alert($(e.target).text());
});

You can find the target element in event.target:

$(document).click(function(event) {
    console.log($(event.target).text());
});

References:


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to dom

How do you set the document title in React? How to find if element with specific id exists or not Cannot read property 'style' of undefined -- Uncaught Type Error adding text to an existing text element in javascript via DOM Violation Long running JavaScript task took xx ms How to get `DOM Element` in Angular 2? Angular2, what is the correct way to disable an anchor element? React.js: How to append a component on click? Detect click outside React component DOM element to corresponding vue.js component