Javascript DOM Event target Property get tag name

Introduction

Using the event.target property together with the element.tagName property to find out which element triggered a specified event:

var x = event.target.tagName;

Click on any elements in this document to find out which element triggered the onclick event.

View in separate window

<!DOCTYPE html>
<html>
<body onclick="myFunction(event)">
<button>This is a button</button>
<p id="demo"></p>
<script>
function myFunction(event) {/*  w  ww.j a  v  a  2 s  .c  om*/
  var x = event.target;
  document.getElementById("demo").innerHTML = "Triggered by a " + x.tagName + " element";
}
</script>

</body>
</html>



PreviousNext

Related