Q:

Javascript: Change word colors depending on the word?

Sorry, this is a bit of a confusing problem.
I want to change the background color of words in a sentence depending on what the word is.
I want the user to be able to enter words like with a text area, but text areas don't support word background colors.
At the moment I can only think of super bootleg solutions such as this:

var div = document.getElementById("div");

function highlight() {
  var words = div.textContent.split(" ");
  div.innerHTML = "";
  for (var i = 0; i < words.length; i++) {
    if (words[i] === "good") {
      div.innerHTML += "<span style=\"background-color: green;\">" + words[i] + "</span> ";
    } else if (words[i] === "bad") {
      div.innerHTML += "<span style=\"background-color: red;\">" + words[i] + "</span> ";
    } else {
      div.innerHTML += "<span>" + words[i] + "</span> ";
    }
  }
  var range = document.createRange();
  var sel = window.getSelection();
  range.setStart(div.lastChild, 1);
  range.collapse(true);
  sel.removeAllRanges();
  sel.addRange(range);
};
div.addEventListener("input", highlight);
highlight();
div {
  background-color: black;
  box-sizing: border-box;
  color: white;
  height: 128px;
  padding: 16px;
  width: 100%;
}
<div id="div" contenteditable="true">good and bad colors</div>

The word 'good' gets a green background, and the word 'bad' gets a red background.
However, this is very glitchy and horrible, so I'm hoping there is a better way do do this.
Any help would be really fantastic!

A:

Try using array methods instead, they're far nicer to work with than for loops:

const div = document.getElementById("div");
function highlight() {
  const words = div.textContent.split(" ");
  div.innerHTML = "";
  words.forEach((word) => {
    const span = div.appendChild(document.createElement('span'));
    span.textContent = word + ' ';
    if (word === 'good') span.classList.add('green');
    if (word === 'bad') span.classList.add('red');
  });
};
div.addEventListener("blur", highlight);
highlight();
div {
  background-color: black;
  box-sizing: border-box;
  color: white;
  height: 128px;
  padding: 16px;
  width: 100%;
}
.green {
  background-color: green;
}
.red {
  background-color: red;
}
<div id="div" contenteditable="true">good and bad colors</div>

