Raz
Raz

Reputation: 319

How to add font awesome icon dynamically from JS file?

I'm trying to add font awesome icons to my greeting function so in every greeting title a different font awesome icon will be attached.

I tried doing it the traditional way but but javaScript prints the html as text and now the title looks like this:

Good Morning<i class="fas fa-sun"></i> 

```javascript
function goodSomething() {

  let today = new Date();
  let curHr = today.getHours();

  if (curHr < 12) {
    document.getElementById('greetings').innerText = "Good Morning" + '<i class="fas fa-sun"></i>';
  } else if (curHr < 18) {
    document.getElementById('greetings').innerText = "Good Afternoon" + '<i class="fas fa-coffee"></i>';
  } else {
    document.getElementById('greetings').innerText = "Good Evening" + '<i class="fas fa-moon"></i>';
  }
};

I expect the output of:

good morning + (sun icon)

good afternoon + (coffee icon)

good evening + (moon icon)

Upvotes: 3

Views: 9410

Answers (1)

Maheer Ali
Maheer Ali

Reputation: 36564

You should use innerHTML instead of innerText you want changing html not text of element.

<i class="fas fa-sun"></i>  //This is string representing html

Below are two snippets which will show the difference

Non-Working Code

document.getElementById("test").innerText = `<i class="fas fa-sun">`
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">


<div id="test"></div>

Working Code

document.getElementById("test").innerHTML = `<i class="fas fa-sun">`
<div id="test"></div>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">

Also you can cleaner and dynamic by using a array of objects.

function goodSomething() {
  let curHr = new Date().getHours();
  const conds = [
        {cond:curHr < 12, icon:"sun", time:"Morning"},
        {cond:curHr < 18, icon:"coffee", time:"Afternoon"},
        {cond:true, icon:"moon", time:"Evening"}
  ]
  let {time,icon} = conds.find(x => x.cond);
  document.getElementById('greetings').innerHTML = `Good ${time} <i class="fas fa-${icon}"></i>`
  
};

Upvotes: 3

Related Questions