Bentley4
Bentley4

Reputation: 11038

Get any html element clicked on using this and jQuery

The following code shows the text of any p element clicked on:

$("p").click(function(){
    console.log($(this).text());
});

But I'd like to generalize this and get the text of any html element clicked on, not just p. I did the following but this returns the text of all html elements on the page:

$("*").click(function(){
    console.log($(this).text());
});

Upvotes: 0

Views: 59

Answers (3)

Itay
Itay

Reputation: 16785

You need to stop the event's propagation so only the clicked element will raise this event and not all of its containers as well.

$("*").click(function(e){
    e.stopPropagation();
    console.log($(this).text());
});

This is proabably more suitable:

$(document).on('click', '*', function(e){
    e.stopPropagation();
    console.log($(this).text());
});

jsFiddle Demo

Upvotes: 3

You clicked on body tag as you have included *

Try

$("*").click(function(e){
    console.log(e.target.innerHTML);
});

innerHTML

event.target

Upvotes: 1

Anton
Anton

Reputation: 32591

Try this

$('*').on('click', function (e) {
    if (e.target == this) {
        console.log($(this).text());
    }
});

Upvotes: 1

Related Questions