javascript - DOM find ID returns undefined -


i getting undefined error whenever click body elements. not sure where's issue..

$('body').on('click',function() {     console.log($(this).attr('id')); }) 

in jquery event callbacks this context equal object on assign event. $('body').on('click' callback this body dom element, wherever user clicked.

if want top clicked element, need access event's target property:

$('body').on('click', function(e) {     console.log(e.target.id); // "" if no id presented });  

check snippet out:

$('body').on('click', function(e)  {     $("#result").text(e.target.id === "" ? "no id" : e.target.id);  }); 
div {    display: inline-block;    width: 50px;    height: 50px;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>    <div style="background-color: red;" id="red"></div>  <div style="background-color: green;" id="green"></div>  <div style="background-color: blue;" id="blue"></div>  <div style="background-color: black;" id="black"></div>  <div style="background-color: yellow;"></div>    <br/><span id="result"></span>


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -