Reputation: 65
I want to select an element by a particular class name (the element holds multiple classes). I have referenced this answer but did not work for me.
<i class="fas fa-star fa-lg clicked"></i>
<i class="fas fa-star fa-lg"></i>
<i class="fas fa-star fa-lg"></i>
clicked
is a custom class with color:red
inside.
Javascript code:
$("i").click(()=> {
changeColor();
})
const changeColor = () => {
if (!$(this).hasClass('clicked')) {
console.log('not clicked class')
}
}
or
const changeColor = () => {
if ($("i:not(.clicked)")){
console.log("no clicked class")
}
}
Both implementations do not work. If you know why, please let me know.
Upvotes: 1
Views: 77
Reputation: 17190
You are not capturing the this
reference correctly, arrow notation can't use the implicit this
reference, avoid using it with jQuery
:
An arrow function expression has a shorter syntax than a function expression and does not have its own
this
,arguments
,super
, ornew.target
. These function expressions are best suited for non-method functions, and they cannot be used as constructors.
I have reworked your code so it can work as you expect:
$("i").click(function()
{
changeColor($(this));
});
const changeColor = (obj) =>
{
if (!obj.hasClass('clicked'))
console.log('not clicked class');
}
.as-console {background-color:black !important; color:lime;}
.clicked {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<i class="fas fa-star fa-lg clicked">Button 1</i>
<i class="fas fa-star fa-lg">Button 2</i>
<i class="fas fa-star fa-lg">Button 3</i>
Upvotes: 4
Reputation: 2127
Instead of mentioned this
you can use event.currentTarget
instead:
$("i").click(function(event)
{
changeColor($(event.currentTarget));
});
const changeColor = ($element) =>
{
if (!$element.hasClass('clicked'))
console.log('not clicked class');
}
.clicked {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<i class="fas fa-star fa-lg clicked">Button 1</i>
<i class="fas fa-star fa-lg">Button 2</i>
<i class="fas fa-star fa-lg">Button 3</i>
Using this
in the code can be confusing because you need to have good knowledge how it works. Many people tend to not use it because of that.
Bear in mind that I renamed the obj
to $element
. I strongly recommend to use $
prefix to show that this variable holds a jQuery.
Upvotes: 1