w3resource

jQuery Events: Display the tag name of the clicked element

jQuery Events : Exercise -21 with Solution

Display the tag name of the clicked element.

HTML code:

<body>
  <p></p>
  <h2>This is a heading 2</h2>
  <div>
  First name: <input type="text"><br>
  Last name: <input type="text">
  </div><br></body>

Solution:

HTML Code :

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
  <meta charset="utf-8">
  <title>Display the tag name of the clicked element</title>
</head>
<body>
  <p></p>
  <h2>This is a heading 2</h2>
  <div>
 First name: <input type="text"><br>
 Last name: <input type="text">
</div>
</body>
</html>

JavaScript Code :


$( "*", document.body ).click(function( event ) {
  event.stopPropagation();
  var domElement = $( this ).get( 0 );
  $( "p:first" ).text( "Clicked on - " + domElement.nodeName );
});

Live Demo:

See the Pen jquery-events-exercise-21 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Set background color of an element when the element (or any elements inside it) gets focus or loses focus.
Next: Count the number of specific elements.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.