w3resource
jquery exercises

jQuery: Display the tag name on click

jQuery Events : Exercise-13 with Solution

Display the tag's name on click.

Sample Data :

<body>
<h1>Heading1</h1>
<h2>Heading2</h2>  
<p>Paragraph</p>
<button>Button</button>
<div id="log"></div>  
</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's name on click</title>
</head>
<body>
<h1>Heading1</h1>
<h2>Heading2</h2>  
<p>Paragraph</p>
<button>Button</button>
<div id="log"></div>  
</body>
</html>

JavaScript Code :


$( "body" ).click(function( event ) {
  $( "#log" ).html( "Clicked a  " + event.target.nodeName );
});

Live Demo:

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


Contribute your code and comments through Disqus.

Previous: Return previous values of custom events.
Next: Count the number of milliseconds between the two click events on a paragraph.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming