Javascript DOM HTML Element tagName Property get from event target

Introduction

Using the tagName property together with the event.target 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)">
<h1>This is a heading</h1>

<button>This is a button</button>

<span>A span element</span>

<p id="demo"></p>

<script>
function myFunction(event) {/*w  w w . ja  v  a 2  s. com*/
  var x = event.target;
  document.getElementById("demo").innerHTML = "Triggered by a " + x.tagName + " element";
}
</script>

</body>
</html>



PreviousNext

Related