I’m writing an application and I need to return a class of an element that I have clicked on.
Problem is that once I click on an element, I also get all of it’s parents classes.
Code I use to retrieve class names:
$('div').click(function () {
console.log($(this).attr("class"));
});
This is a sample of elements:
<div class="parent">
<div class="child">
Bla bla bla
</div>
</div>
Once I click on a .child div, it returns me both .child and .parent class names.
I suppose there should be an easy way to fix this, but after a couple of hours of research I couldn’t find anything.
You need to prevent the event from bubbling to the parent elements, use
return false;return falsefrom within a jQuery event handler is effectively the same as calling bothe.preventDefaultande.stopPropagationon the passed jQuery.Event object. ……..Read this excellent answer for more info.
With
<div>there is now difference betweene.stopPropagation()andreturn falsebecause<div>doesn’t have a default click event like<a>or <button>do.