1

I am trying to replace all font awesome icon within a certain div.

Here is my code:

$( '#icons' ).find( '.fa' ).each( function() {
  if( $( this ).hasClass( 'fa-adjust' ) ){
    $( this ).attr( 'class' , 'fa fa-circle' );
  } else if( $( this ).hasClass( 'fa-circle' ) ){
    $( this ).attr( 'class' , 'fa fa-adjust' );
  }
});

What I would like to do is swap fa-adjust with fa-circle within the div icons.

2
  • what is the problem with your own code ? Commented Nov 30, 2014 at 13:03
  • it is not swapping the classes. i forgot to mention, that the classes could be several div's below icons... does this matter? Commented Nov 30, 2014 at 13:15

3 Answers 3

1

Use toggleClass function. It can toggle several classes:

$( '#icons' ).find( '.fa' ).toggleClass('fa-adjust fa-circle');
Sign up to request clarification or add additional context in comments.

Comments

0

Just do it straight away, as you can't have duplicate ids. Is icons a class?

$('.fa-adjust').removeClass("fa-adjust").addClass("fa-circle");

1 Comment

No, icons is a div so I want to swap all of the fa-adjust and fa-circle within the div icons.
0
$('#icons').find('.fa.fa-adjust, .fa.fa-circle').toggleClass('fa-adjust fa-circle');

But why do you have to do it with JS rather than modify the markup?

2 Comments

I am getting the updates from an ajax call and would like to change the icon to reflect the refreshed states.
Got it. You don't have to call each because toggleClass will perform a so-called implicit iteration - jQuery automatically iterates over all the elements in a selection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.