Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

125
Visualizações
Changing Font Awesome icon through dataset

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>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

const changeIcon = () => {
  element.dataset.content = String.fromCharCode(0xf0c2);
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda