For every click, an event will be triggered and that event contains all the info about the element. So, we obviously have to catch that event to get the element info and it can be easily done with JS.

When clicking any element then it triggers an event and we can find the element details using the event.target.

Following is the example code with both jQuery and without jQuery.

With jQuery

$(document).click(function(event) {

// The following the line of code gets the text of an element.
// Event.target gets the element details
var textData = $(event.target).text();
});

Without jQuery

document.addEventListener('click', function(e) {
e = e || window.event;
var targetElement = e.target || e.srcElement,
text = targetElement.textContent || targetElement.innerText;
}, false);

The above event listeners might not work in some of the browsers such as those less than IE9. So, instead of addEventListener() we might need to use the attachEvent().

Categorized in:

Tagged in: