Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
144
rated 0 times [  146] [ 2]  / answers: 1 / hits: 16706  / 10 Years ago, wed, february 11, 2015, 12:00:00
<html>
<head>

<script type=text/javascript>
function getElement(e) {
var element = e.target || e.srcElement;
alert(element.id);
}
</script>

</head>
<body onclick=getElement()>

<div id=div1></div>
<div id=div2></div>

</body>
</html>


Tried this to get the ID of element clicked and alert it.
I'm sure it's something pretty basic I'm missing.



Can anyone help?


More From » javascript

 Answers
2

It's actually pretty basic, stop using inline event handlers



<!DOCTYPE html>
<head>
<title>It works</title>
</head>
<body>

<div id=div1></div>
<div id=div2></div>

<script type=text/javascript>
document.addEventListener('click', function(e) {
alert( e.target.id );
}, false);
</script>
</body>
</html>


FIDDLE


[#67877] Sunday, February 8, 2015, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kinsleyashlynnh

Total Points: 64
Total Questions: 119
Total Answers: 98

Location: Burundi
Member since Sat, Aug 21, 2021
3 Years ago
;