-1

I have been googling for answers and though I do see similar questions posted on Stack, none seem to fit what I'm looking for.

For example with the code below:

HTML

<div class="container">
<h1>Is it morning, afternoon, evening, or night?</h1>
</div>

Javascript

const header = document.getElementByTagName("h1").textContent;
function colorWords()
{
 if (header.indexOf("morning"){
  header.style.color = "yellow";
  });

The end result that I'm trying to achieve is to make the font color different for the words, "morning," "afternoon," and "evening." I was thinking of doing either for loops or using methods ie .indexOf, .search to find those specific words and then using an if-else statement/switch to change the color but I'm not fully sure how to implement this.

Thank you in advance!

KO-d14
  • 115
  • 7

1 Answers1

0

You could use regex here

const header = document.querySelector("h1");

header.innerHTML = header.innerHTML.replace(/(morning|afternoon|evening|night)/g, `<span class ="$1">$1</span>`)
.morning {
  background-color: gray;
}

.afternoon {
  background-color: yellow;
}

.evening {
  background-color: red;
}

.night{
  background-color: black;
  color: white;
}
<div class="container">
  <h1>Is it morning, afternoon, evening, or night?</h1>
</div>
DecPK
  • 24,537
  • 6
  • 26
  • 42
  • Hi decpk, Sorry for the late response, I wanted to understand the answer so I was looking online. (I know now what the '$1' means.) I appreciate how your answer was easy to understand and to the point! Thank you! :) – KO-d14 Jun 15 '21 at 01:24