is there anyway to get the class when click event is fired. My code as below, it only work for id but not class.
$(document).ready(function() {_x000D_
$("a").click(function(event) {_x000D_
alert(event.target.id + " and " + event.target.class);_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
<a href="#" id="kana1" class="konbo">click me 1</a>_x000D_
<a href="#" id="kana2" class="kinta">click me 2</a>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
jsfiddle code here
This question is related to
javascript
jquery
jquery-events
$(document).ready(function() {_x000D_
$("a").click(function(event) {_x000D_
var myClass = $(this).attr("class");_x000D_
var myId = $(this).attr('id');_x000D_
alert(myClass + " " + myId);_x000D_
});_x000D_
})
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<a href="#" id="kana1" class="konbo">click me 1</a>_x000D_
<a href="#" id="kana2" class="kinta">click me 2</a>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
This works for me. There is no event.target.class function in jQuery.
This will contain the full class (which may be multiple space separated classes, if the element has more than one class). In your code it will contain either "konbo" or "kinta":
event.target.className
You can use jQuery to check for classes by name:
$(event.target).hasClass('konbo');
and to add or remove them with addClass and removeClass.
If you are using jQuery 1.7:
alert($(this).prop("class"));
or:
alert($(event.target).prop("class"));
You will get all the class in below array
event.target.classList
Careful as target
might not work with all browsers, it works well with Chrome, but I reckon Firefox (or IE/Edge, can't remember) is a bit different and uses srcElement. I usually do something like
var t = ev.srcElement || ev.target;
thus leading to
$(document).ready(function() {
$("a").click(function(ev) {
// get target depending on what API's in use
var t = ev.srcElement || ev.target;
alert(t.id+" and "+$(t).attr('class'));
});
});
Thx for the nice answers!
Source: Stackoverflow.com