Reputation: 11038
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
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());
});
Upvotes: 3
Reputation: 57105
You clicked on body
tag as you have included *
Try
$("*").click(function(e){
console.log(e.target.innerHTML);
});
Upvotes: 1
Reputation: 32591
Try this
$('*').on('click', function (e) {
if (e.target == this) {
console.log($(this).text());
}
});
Upvotes: 1