w3resource

jQuery: Find the class of the clicked element

jQuery Practical exercise Part - I : Exercise-44

Find the class of the clicked element.

Sample Solution:

HTML Code :

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-git.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Find  the class of the clicked element.</title>
</head>
<body>
<p>Click on the color and get the class name.</p>
<ul class="tabs">
<li class="ff0000">Red</li>
<li class="000000">Black</li>
<li class="ffd700">Gold</li>
</ul>
</body>
</html>

JavaScript Code:

$("li").click(function() {
   var colorClass = this.className;
   console.log(colorClass);
});

See the Pen jquery-practical-exercise-44 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Set a value in a span using jQuery.
Next: Set href attribute at runtime using jquery.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/jquery-exercises/part1/jquery-practical-exercise-44.php