0

I'm trying to change a Font Awesome icon on action using JS. I'm implementing the icon through pseudo element ::before.

Assigning the icon through CSS using content:'\f0c2' displays the icon fine, but if I transfer the string through a dataset - content: attr(data-content), it just renders the string on the page.

How can I get it to work? Is there a better way to do it?

Here's a JSFiddle with all relevant code I've used.

const element = document.querySelector('.data');
const btn = document.querySelector('.btn');

const changeIcon = () => {
  element.dataset.content = '\\f185';
}

btn.addEventListener('click', changeIcon);
.container {
  display: grid;
  place-items: center;
  margin-top: 6rem;
  font-family: sans-serif;
  color: lightblue;
  gap: 1rem;
}

.btn {
  padding: 1em 2em;
  background-color: lightblue;
  color: white;
  border-radius: 10px;
}

.btn:hover {
  background-color: white;
  color: lightblue;
  border: 1px solid lightblue;
}

.icon-before::before {
  display: inline-block;
  text-rendering: auto;
  -webkit-font-smoothing: antialiased;
  font: var(--fa-font-solid);
  margin-right: 0.2em;
}

.string::before {
  content: '\f0c2';
}

.data::before {
  content: attr(data-content);
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<div class='container'>
  <h2 class='element string icon-before'>
    Added through string
  </h2>
  <h2 class=' element data icon-before' data-content="\f0c2">
    Added through dataset
  </h2>
  <a class='btn'>Press Me</a>
</div>
evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
XanderTEM
  • 81
  • 10
  • also: [Using attr(data-icon) property to display unicode before element](https://stackoverflow.com/questions/30097807/using-attrdata-icon-property-to-display-unicode-before-element) – pilchard Jun 24 '22 at 23:17

1 Answers1

1
const changeIcon = () => {
  element.dataset.content = String.fromCharCode(0xf0c2);
}
IT goldman
  • 14,885
  • 2
  • 14
  • 28