Mark Carpenter Jr Mark Carpenter Jr - 25 days ago 5
Javascript Question

jQuery function chaining with class based conditional, Possible?

So I have a block of jQ that swaps out some classes and adjusts the style of a button when triggered by the user.

It looks like this,

// Initial object selection
$(b)
// Select the Icon
.siblings('i')
// add class of new icon
.addClass('fa-check-square-o')
// remove class of old icon
.removeClass('fa-square-o')
// select the parent element (label)
.closest('label')
// adjust for the size change of the icon
.css('padding-right', '3px')
// add the new button contextual class
.addClass('btn-success')
// remove possible old contexual button classes
.removeClass('btn-danger btn-warning');


This works as expected, however, I have another case where a button might have a contextual
'btn-info'
class and I would like to determine if that class is present on the
'label'
element.

I thought I could do;

// ... jQ chain above ...
// remove possible old contextual button classes
.removeClass('btn-danger btn-warning')
// Conditonally check 'label' if it has class
.hasClass('btn-info')
// 'label' has the class... Do Stuff
.removeClass('btn-success btn-warning btn-danger');


But I get an error, "... removeClass() is not a function"

I also tried with
.has('.btn-info')
in place of
.hasClass()
and I don't get the error but I do not get the expected result of the other 3 classes being removed leaving the
'btn-info'
class.

Is this a logical workflow with chaining, do I have the right expectations or am I asking too much form jQ?

Thoughts much appreciated.




Html markup for good measure,

Just a simple bootstrap button group

<div class="btn-group btn-group-xs" data-toggle="buttons">
<label class="btn btn-success">
<input type="radio" name="options" id="ynna-yes" autocomplete="off">
<i class="fa fa-square-o fa-lg"></i>
</label>
<label class="btn btn-danger">
<input type="radio" name="options" id="ynna-no" autocomplete="off">
<i class="fa fa-square-o fa-lg"></i>
</label>
<label class="btn btn-info">
<input type="radio" name="options" id="ynna-na" autocomplete="off">
<i class="fa fa-square-o fa-lg"></i>
</label>
</div>

Answer Source

hasClass() returns a boolean so what you want to use is filter() which will return the matched elements.

.removeClass('btn-danger btn-warning')
.filter('.btn-info')
  .removeClass('btn-success btn-warning btn-danger');