# Methods

Reference for JavaScript methods available in the Font Awesome API.

> Below are the methods available in the Font Awesome Javascript API.

Make sure you already:

- [Set up access](/apis/javascript.md) to the Javascript API in your project.

## counter(content, params)

_Add counters to layers._

```js
import { faEnvelopeSquare } from '@fortawesome/free-solid-svg-icons'
import { layer, icon, counter } from '@fortawesome/fontawesome-svg-core'
layer((push) => {
  push(icon(faEnvelopeSquare))
  push(counter('5'))
}).html
```

### Params

Allow the following keys (see [icon()](/apis/javascript/methods.md#icon-icondefinition-params)):

| Name         |
| :----------- |
| `classes`    |
| `attributes` |
| `styles`     |
| `title`      |

## dom.css()

_Stylesheet definitions required to properly display icons generated by the API in the DOM._

Generates the accompanying CSS that is necessary to correctly display icons. If
you choose to disable `autoAddCss` in the [configuration](/apis/javascript/configuration.md) you'll need to grab
these styles and insert them manually into the DOM.

This is useful and normally paired with [`dom.insertCss()`](/apis/javascript/methods.md#dom-insertcss).

## dom.i2svg(params)

_Will automatically find any `<i>` tags in the page and replace those with `<svg>` elements._

This functionality uses
[`requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame) to batch the updates and increase performance.

```js
import { dom, library } from '@fortawesome/fontawesome-svg-core'
import { fas } from '@fortawesome/free-solid-svg-icons'

library.add(fas)

dom.i2svg()
```

To specify a different element to search:

```js
dom.i2svg({ node: document.getElementById('content') })
```

As of v5.7.0, this method also supports the Promise API:

```js
dom.i2svg().then(function () {
  console.log('Icons have rendered')
})
```

You can also use callbacks that will be triggered when the icons have been rendered:

```js
function iconDoneRendering() {
  console.log('Icons have rendered')
}

dom.i2svg({ callback: iconsDoneRendering })
```

## dom.insertCss()

_Convenience method that will add the given CSS to the DOM `<head>`._

```js
import { dom } from '@fortawesome/fontawesome-svg-core'

const css = dom.css()

dom.insertCss(css)
```

## dom.watch(params)

_Calls dom.i2svg() for you and watches the DOM for any additional icons being added or modified._

  <h4>
   Different default configs
  </h4>

DOM watching is on by default when Font Awesome is loaded from
`@fortawesome/fontawesome-free` or `@fortawesome/fontawesome-pro` but it's
disabled for the `@fortawesome/fontawesome-svg-core`.

This method is useful when you're loading <span class="nowrap">`@fortawesome/fontawesome-svg-core`</span>, but would still like to leverage automatic DOM watching.

### Params

Calling `dom.watch()` without params is equivalent to calling with the following params:

```js
dom.watch({
  autoReplaceSvgRoot: document,
  observeMutationsRoot: document
})
```

| Name                   | Purpose                                                                    |
| :--------------------- | :------------------------------------------------------------------------- |
| `autoReplaceSvgRoot`   | limits the scope for automatic search and replacement of icons.            |
| `observeMutationsRoot` | limits the scope of the mutation observer to the DOM under this root node. |

## findIconDefinition(params)

_Look up an icon definition previously registered in the Library._

### Basic Use

```js
import { findIconDefinition } from '@fortawesome/fontawesome-svg-core'

const faUser = findIconDefinition({ iconName: 'user' })
```

```js
{
  "prefix": "fas",
  "iconName": "user",
  "icon": [
    512,
    512,
    [],
    "f007",
    "M962…-112z"
  ]
}
```

### Specify the prefix as well

```js
findIconDefinition({ prefix: 'fab', iconName: 'fort-awesome' })
```

```js
{
  "prefix": "fab",
  "iconName": "fort-awesome",
  "icon": [
    448,
    512,
    [],
    "f286",
    "M412…999z"
  ]
}
```

You can then feed this as the `iconDefinition` to other functions such as `icon()`.

For additional information, visit [styles] and [aliases] to see how they can be used within `findIconDefinition()`.

  <h4>
   Did You Know?
  </h4>

[Aliases](/web/add-icons/how-to.md#aliases) and the various
[styles](/apis/javascript/methods.md#prefixes-and-style-classes) syntax can
be used within `findIconDefinition()`.

## icon(iconDefinition, params) <a name="icon-icondefinition-params"></a>

_Renders an icon as SVG._

### Basic Use

```js
import { icon } from '@fortawesome/fontawesome-svg-core'
import { faPlus } from '@fortawesome/free-solid-svg-icons'

const faPlusIcon = icon(faPlus)
```

### Advanced Options

Getting the HTML for the icon:

```js
icon(faPlus).html
```

```html
[ '<svg data-prefix="fas" data-icon="user" class="svg-inline--fa fa-user fa-w-16">...</svg>' ]
```

Appending nodes from an [`HTMLCollection`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection):

```js
const faPlusIcon = icon(faPlus)

// Get the first element out of the HTMLCollection
document.appendChild(faPlusIcon.node[0])
```

Abstract tree:

```js
icon(faPlus).abstract
```

```js
;[
  {
    tag: 'svg',
    attributes: {
      'data-prefix': 'fas',
      'data-icon': 'user',
      'class': 'svg-inline--fa fa-user fa-w-16',
      'role': 'img',
      'viewBox': '0 0 512 512'
    },
    children: [
      {
        tag: 'path',
        attributes: {
          fill: 'currentColor',
          d: 'M96…112z'
        }
      }
    ]
  }
]

// The `data-prefix` attribute will only accept short prefix names (ex. fas, far, fal, fat, fad, fass)
```

  <h4>
   Marty, you're not thinking fourth-dimensionally!
  </h4>

The `abstract` value is mostly useful for library / framework / tooling
creators. It provides a data structure that can easily be converted into other
objects.

Using a transform:

```js
icon(faPlus, {
  transform: {
    size: 8, // starts at 16 so make it half
    x: -4, // the same as left-4
    y: 6, // the same as up-6
    rotate: 90, // the same as rotate-90
    flipX: true, // the same as flip-h
    flipY: true // the same as flip-v
  }
}).html
```

  <h4>
   More than meets the eye...
  </h4>

If you need help figuring out transforms, see
[parse.transform](/apis/javascript/methods.md#parse-transform-transformstring).

Use the main icon as a mask for another another icon:

```js
import { icon } from '@fortawesome/fontawesome-svg-core'
import { faPlus, faCircle } from '@fortawesome/free-solid-svg-icons'

icon(faPlus, {
  mask: faCircle
}).html
```

Specify mask ID used to generate the SVG definitions (added in 5.12.2):

**This is useful for testing libraries that use snapshots to verify test results.**

```js
import { icon } from '@fortawesome/fontawesome-svg-core'
import { faPlus, faCircle } from '@fortawesome/free-solid-svg-icons'

icon(faPlus, {
  mask: faCircle,
  maskId: 'circle'
}).html
```

  <h4>
   The title parameter is no longer supported
  </h4>

    With v7's revised accessibility approach, we no longer use prior versions' `title` for auto-accessibility purposes.

    If you're aiming to [make an icon with semantic meaning accessible](/web/dig-deeper/accessibility.md#making-semantic-icons-accessible), we recommend [following our updated accessibility best practices](/web/dig-deeper/accessibility.md).

    If you want to add a `title` attribute on an icon, you can set it as a property on an object assigned to the `attributes` property like any other custom attribute, for example: `{attributes: {title: "foo"}}`.

Additional classes:

```js
icon(faSpinner, {
  classes: ['fa-spin']
}).html
```

```html
<svg data-prefix="fas" data-icon="spinner" class="svg-inline--fa fa-spinner fa-w-16 fa-spin">…</svg>
```

Additional attributes:

```js
icon(faSpinner, {
  attributes: { 'data-component-id': 987654 }
}).html
```

Additional styles:

```js
icon(faSpinner, {
  styles: { 'background-color': 'coral' }
}).html
```

Creating a symbol (auto-generating ID):

```js
icon(faSpinner, {
  symbol: true
}).html
```

Creating a symbol (explicit ID):

```js
icon(faSpinner, {
  symbol: 'spinner-icon'
}).html
```

## layer(assembler, params)

_Allows multiple icons to be assembled together in a layer._

Convenience function for producing the [HTML markup for layers](/web/style/layer.md).
It wraps `icon()`, `text()`, or `counter()` inputs in `<span class="fa-layers fa-fw"></span>`.

```js
import { faSpinner } from '@fortawesome/free-solid-svg-icons'
import { layer, icon } from '@fortawesome/fontawesome-svg-core'

layer((push) => {
  push(icon(faSpinner))
  push(icon(faUser, { transform: { size: 4 } }))
}).html
```

Specify additional classes like this.

```js
import { faSpinner } from '@fortawesome/free-solid-svg-icons'
import { layer, icon } from '@fortawesome/fontawesome-svg-core'

layer(
  (push) => {
    push(icon(faSpinner))
    push(icon(faUser, { transform: { size: 4 } }))
  },
  { classes: ['sign-in-loading'] }
).html
```

### Params

Allow the following keys:

| Name      |
| :-------- |
| `classes` |

## library.add(...iconDefinitions)

_Pre-registering icon definitions so that do not have to explicitly pass them to render an icon._

### Explicitly passing the icon

```js
import { icon } from '@fortawesome/fontawesome-svg-core'
import { faUser } from '@fortawesome/free-solid-svg-icons'
import { fab } from '@fortawesome/free-brands-svg-icons'

icon(faUser)
icon(fab.faFortAwesome)
```

### Using the library

```js
import { icon, library } from '@fortawesome/fontawesome-svg-core'
import { faUser } from '@fortawesome/free-solid-svg-icons'
import { fab } from '@fortawesome/free-brands-svg-icons'

library.add(fab, faUser)

icon({ prefix: 'fas', iconName: 'user' })
icon({ prefix: 'fab', iconName: 'fort-awesome' })
```

### Icon definitions arguments

```js
import { library } from '@fortawesome/fontawesome-svg-core'
import { faUser } from '@fortawesome/free-solid-svg-icons'
import { faFontAwesome } from '@fortawesome/free-brands-svg-icons'

const icons = [faUser, faFontAwesome]

library.add(faUser, faFontAwesome) // multiple arguments
library.add(icons) // works the same!
library.add(...icons) // also works the same!
```

## parse.icon(icon)

_Takes an icon string, an object, or an array and returns an icon definition._

### What is it?

The `parse.icon()` method will allow the user to input an icon's name (or alias) as a string, an object, or an array when calling an icon. See our [Vue docs](/web/use-with/vue/add-icons.md#call-the-icons) for an example.

The `parse.icon()` method also normalizes our styles and icon names. For example, you can reference our solid icons with with a prefix of `'solid'`, `'fa-solid'`, `'fas'`, or `'fa'`.

Additionally, you can reference our icons with just the icon name, which will default to solid style.

### How to Use

Referencing the icon as a string:

```js
import { parse } from '@fortawesome/fontawesome-svg-core'

// the icon's style will default to Solid, it's family will default to Classic
parse.icon('dog')

// returns an object, with the default `fas` prefix
// {prefix: 'fas', iconName: 'dog'}
```

Referencing the icon as an object with a short prefix name:

```js
import { parse } from '@fortawesome/fontawesome-svg-core'

// No additional parsing was needed for this since it started with the prefix and icon name
parse.icon({ prefix: 'fas', iconName: 'dog' }) // {prefix: 'fas', iconName: 'dog'}

// Same deal, no additional parsing is required for the Sharp family either
parse.icon({ prefix: 'fass', iconName: 'cat' }) // {prefix: 'fass', iconName: 'cat'}
```

Referencing the icon as an object with a long prefix name:

```js
import { parse } from '@fortawesome/fontawesome-svg-core'

// a classic solid dog icon
parse.icon({ prefix: 'fa-solid', iconName: 'dog' }) // { prefix: 'fas', iconName: 'dog' }
```

  <h4>
   Style name prefixes
  </h4>

Using a style name prefixed with `fa-` for `prefix` is no longer recommended. Why? Because you can't select the Sharp family.

Referencing the icon as an array with non-prefix:

```js
import { parse } from '@fortawesome/fontawesome-svg-core'

// This only lets you select the Classic family:
parse.icon(['solid', 'dog'])
```

  <h4>
   Don't use style names in array syntax
  </h4>

Using a style name, like `solid` is no bueno in array syntax. Why? Because you can't select the Sharp family.

  <h4>
   Default Style
  </h4>

When calling the icons, if a style (solid, thin, duotone, etc.) is not
specified or there is not a `styleDefault` set, the icon's class and style
will default to `solid`.

#### Style Prefixes

Here's a complete list of our icon families and styles along with how you can reference them using style prefixes.

Read more about our [basic styling](/web/add-icons/how-to.md#basics) or how [aliases](/web/add-icons/how-to.md#aliases) can be used in conjunction with the styling.

## parse.transform(transformString)

_Takes a Power Transform string and produces the normalized transform object used by the API._

  <h4>
   Up, Up, Down, Down, Left, Right, Left, Right, B, A
  </h4>

This is an internal method that you probably won't need but it might be useful
to know how the translation happens.

Power Transforms are space-separated _verbs_ and _values_.

### Transform verbs

| Verb   | What it does                    |
| :----- | :------------------------------ |
| grow   | Makes the icon larger           |
| shrink | Makes the icon smaller          |
| left   | Move the icon to the left       |
| right  | Move the icon to the right      |
| up     | Move the icon up                |
| down   | Move the icon down              |
| rotate | Rotate the icon left or right   |
| flip-v | Flips along the vertical axis   |
| flip-h | Flips along the horizontal axis |

### Transform Values

Font Awesome 5 icons are built on a sixteen pixel grid. For **size and movement** values represent 1 unit out of 16.

For example, `up-2` means "move the icon up 2 units". If the icon happens to be 16px high this will result in the icon being moved up by 2 pixels.

### Converting to SVG transform values

Power Transform string are easy to use and compose but must be converted into a format that is useful to perform SVG transforms.

```js
import { parse } from '@fortawesome/fontawesome-svg-core'

parse.transform('grow-2 left-4 rotate-15')
```

The following data is what gets used when rendering icons.

```js
{
  "size": 18,
  "x": -4,
  "y": 0,
  "flipX": false,
  "flipY": false,
  "rotate": 15
}
```

## text(content, params)

_Add text to layers._

```js
import { faSpinner } from '@fortawesome/free-solid-svg-icons'
import { layer, icon, text } from '@fortawesome/fontawesome-svg-core'

layer((push) => {
  push(icon(faSpinner))
  push(text('Wait…', { transform: { size: 4 } }))
}).html
```

### Params

Allow the following keys (see [icon()](/apis/javascript/methods.md#icon-icondefinition-params)):

| Name         |
| :----------- |
| `transform`  |
| `title`      |
| `classes`    |
| `attributes` |
| `styles`     |

## toHtml(abstractElement)

_Convenience method to convert an abstract representation of a Font Awesome object into its corresponding HTML markup._

The `icon()`, `text()`, `layer()`, and `counter()` functions each return a Font Awesome object that has properties `abstract` and `html`. (See also the [documentation for icon()](/apis/javascript/methods.md#icon-icondefinition-params) more details about the shape of such objects.)

`toHtml()` can be used to transform any abstract element into HTML.
