Andes Rizky Nugroho
Andes Rizky Nugroho

Reputation: 15

Renaming the front of the class attribute with javascript / jquery

I have old documents that still use font attributes awosome v3.2.1 that all classes have first name the icon. If I use the new version would be very inconvenient if I had to rename the class one by one manually. HTML markup:

<a class="btn" href="#"><i class="icon-info-sign"></i> Info</a>
<a class="btn" href="#"><i class="icon-trash"></i> Delete</a>
<a class="btn" href="#"><i class="icon-cog"></i> Settings</a>

How can the results as below

<a class="btn" href="#"><i class="fa fa-info-sign"></i> Info</a>
<a class="btn" href="#"><i class="fa fa-trash"></i> Delete</a>
<a class="btn" href="#"><i class="fa fa-cog"></i> Settings</a>

Help from anyone would be invaluable

Upvotes: 0

Views: 51

Answers (2)

yuriy636
yuriy636

Reputation: 11661

You can replace the classnames like this:

var icons = document.querySelectorAll('[class^=icon]');
for (icon of icons){
  icon.classList.value = icon.classList.value.replace('icon-','fa fa-');
  console.log(icon.classList.value);
}
<a class="btn" href="#"><i class="icon-info-sign"></i> Info</a>
<a class="btn" href="#"><i class="icon-trash"></i> Delete</a>
<a class="btn" href="#"><i class="icon-cog"></i> Settings</a>

  • Select all the elements that have a classname starting with "icon"
  • For...of loop to iterate each icon, and replace its classname with where "icon-" with "fa fa-"
  • Optional console.log

I would still do it the @richb01 way: find & replace directly in the code editor, much cleaner.

Upvotes: 0

&#214;zg&#252;r Ersil
&#214;zg&#252;r Ersil

Reputation: 7013

basically you can do it with jquery method switchClass like that

$("a i").each(function(item){
   $(item).switchClass( "icon-info-sign", "fa fa-info-sign" );
   $(item).switchClass( "icon-trash" , "fa fa-trash" );
   $(item).switchClass( "icon-cog", "fa fa-cog" );
}

Upvotes: 1

Related Questions