Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

118
Views
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 answers
Answer question

0

const changeIcon = () => {
  element.dataset.content = String.fromCharCode(0xf0c2);
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!