简体   繁体   中英

Detect what div 'id' or 'class' was clicked on page without jQuery

Is there a way to write an event on the page to listen for any and all clicks on the page and return their id or class name. I can't seem to find anything that does it without the use of jQuery. Example:

document.body.addEventListener('click', function(event)
    console.log(event.target.id)
    console.log(event.target.className);
});

Seems very simple but I am just having a hard time getting it to work. I have tried setting the event listener to the window as well.

document.body.addEventListener('click', function(event){
    console.log(event.target.id)
    console.log(event.target.className);
});

missing {

I figured it out. I was clicking inside of an iframe and therefor it wasn't returning any values. Works outside of an iframe like intended. Thanks all!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM