Mark Carpenter Jr Mark Carpenter Jr - 5 months ago 17
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
// Select the Icon
// add class of new icon
// remove class of old icon
// select the parent element (label)
// adjust for the size change of the icon
.css('padding-right', '3px')
// add the new button contextual class
// 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
class and I would like to determine if that class is present on the

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
// '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
in place of
and I don't get the error but I do not get the expected result of the other 3 classes being removed leaving the

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 class="btn btn-danger">
<input type="radio" name="options" id="ynna-no" autocomplete="off">
<i class="fa fa-square-o fa-lg"></i>
<label class="btn btn-info">
<input type="radio" name="options" id="ynna-na" autocomplete="off">
<i class="fa fa-square-o fa-lg"></i>

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')
  .removeClass('btn-success btn-warning btn-danger');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download