简体   繁体   中英

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)

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>`

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM