Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
166
rated 0 times [  171] [ 5]  / answers: 1 / hits: 7880  / 5 Years ago, sun, april 14, 2019, 12:00:00

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)


More From » dom

 Answers
3

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

};

[#8013] Thursday, April 11, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lailab

Total Points: 706
Total Questions: 102
Total Answers: 95

Location: Falkland Islands
Member since Mon, Jul 13, 2020
4 Years ago
;