Andes Rizky Nugroho Andes Rizky Nugroho - 3 months ago 9
HTML Question

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

Answer

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.