Font Awesome pairs well with jQuery, especially if you are using Web Fonts. But if you’re using SVG + JS, you’ll need to make a few adjustments.
We’ll cover how SVG works and what you need to integrate with jQuery successfully. Below we’ll describe an easy option using nesting. If nesting doesn’t work for you, we’ve got some more information and alternate options that can get you going.
Nesting SVG Tags Within Their Parent
A quick way to reduce issues with libraries like jQuery is to allow the SVG tags to nest within the parent tag, which will allow event binding and other DOM manipulation to function.
First, we need to configure Font Awesome SVG with JavaScript to nest by adding data-auto-replace-svg="nest" to the core script:
Or if you’re using the all.js:
If we then add an <i> tag to the page:
The SVG icon is rendered within the <i> tag:
Alternatives to Nesting
If you don’t nest, here’s what you need to know… The library seeks out tags that look like icons:
They are replaced with a new svg element:
How Does This Happen?
The Font Awesome javascript looks for Font Awesome HTML DOM elements by looking at CSS classes, like fas, fa-solid or fa-dragon.
It figures out things like the style prefix (fas or fa-solid), the icon (dragon), and any styling utilities on the element.
It schedules the replacement of the <i> element for the next convenient time.
When the browser is ready the <i> DOM element is replaced with a new <svg> element.
A comment is added below the new <svg> element representing the original HTML for convenience.
Why Is This Important?
Since elements are replaced, any bindings to the element will be lost!
The example below will not work:
The example below will work because it is not dependent on the <i> element:
Attaching Events to the Icon
If you absolutely need to attach events to the icon, you can use the
data-fa-i2svg attribute, but you need to allow for the dynamic creation of the
SVG element.
You can attach the event to an ancestor and filter for the icon:
This will not work and will leave you sad:
Changing Icons by Changing Classes
If you want to swap out an icon, you can do that by changing the classes on the element, like this: