Reputation: 5166
I want to change the icon when a user clicks a button, so first I need to find which icon the button has, determined by the name of the class.
I'm currently able to change the icon to something else, but when I try to *find* the class, it's not working.
I'm currently testing by showing an alert if the span has the right class, but it's not alerting. What am I doing wrong?
<button class="btn btn-primary">
<span class="fa fa-user-plus text-muted"></span>
</button>
$(document).on('click', '.follow', function(e) {
var button = $(this);
if(button.find('span').hasClass('fa-user-plus')) {
alert();
// won't alert!
}
});
The following code works; I'm able to change the icon to a spinner, so I know the button > span targeting is correct. I'm just not able to determine what class the span has.
button.find('span').removeClass('fa-user-plus').addClass('fa-spinner fa-spin');
Upvotes: 2
Views: 1887
Reputation: 2845
Try this, I hope it'll help you out. Thanks
$('.btn').click(function() {
var child = $(this.children)
if(child.hasClass('fa-user-plus')) {
child.removeClass('fa-user-plus').addClass('fa-spinner fa-spin');
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn btn-primary">Button
<span class="fa fa-user-plus text-muted"></span>
</button>
Upvotes: 1
Reputation: 10184
You are not getting handle to the button correctly - $(this) gives you handle to the DOM, not the button. JQuery $(this)
has different meanings in different contexts. You can get the button handle using an ID for example. See the following working snippet.
Edit:
I just read your comment. Accessing your button with the ID was just an example. You can access it with the CSS classes too. E.g. $('.btn.btn-primary')
. See the edited snippet below.
if($('.btn.btn-primary').find('span').hasClass('fa-user-plus')) {
console.log("found");
// won't alert!
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn btn-primary">
<span class="fa fa-user-plus text-muted"></span>
</button>
Upvotes: 1
Reputation: 4401
Add the class "follow" to the button and use it as trigger:
HTML:
<button class="btn btn-primary follow">
<span class="fa fa-user-plus text-muted"></span>
</button>
JQUERY:
$(document).on('click', '.follow', function(e) {
var button = $(this);
if(button.find('span').hasClass('fa-user-plus')) {
alert('hi');
// won't alert!
}
});
Upvotes: 1