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.
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.
data-auto-replace-svg="nest" to the core script:
Or if you're using the
If we then add an
<i> tag to the page:
The SVG icon is rendered within the
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
How Does This Happen?
- It figures out things like the style prefix (
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
- 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
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
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: