0

I would like the output to look like this:

stephen

peter

ben

but with the 'e' characters having a background colour. Is this possible using the below code and some javascript?

<!DOCTYPE html>
<html>
<head>
</head>
<body>


<div>
stephen
<p id="demo">peter</p>
ben
</div>


<script>

</script>
</body>
</html>
Steve
  • 625
  • 2
  • 5
  • 17
  • _"Is this possible using the below code and some javascript?"_ - yes. See [`Node.nodeType`](https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType) and [`Node.childNodes`](https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes). – Joseph Jun 19 '19 at 21:06

2 Answers2

1

Get the names, split them into letters, pass each letter through a comparison function and add a span with the highlight class if it is an e.

var names = document.querySelectorAll('p');

names.forEach(function(name){
  var letters = name.innerText.split('');
  var newName = '';
    letters.forEach(function(letter){
    newName += isE(letter);
  })
  name.innerHTML = newName;
})

function isE(letter){
let newStr =''
  letter.toLowerCase() == 'e'
    ? newStr += '<span class="highlight">'+ letter +'</span>'
    : newStr = letter;
  return newStr;
}
.highlight {
  background-color: yellow
}
<p id="demo1">stephen</p>
<p id="demo2">peter</p>
<p id="demo3">ben</p>
gavgrif
  • 15,194
  • 2
  • 25
  • 27
0

And my solution

const elementDiv = document.querySelector('div');
const elementText = elementDiv.textContent.trim().split(/\s+/);

elementDiv.innerHTML = '';

elementText.forEach(element => {
  elementDiv.innerHTML += `<br>${element.replace(/e/gi, '<span style="color: red;">e</span>')}`;
});
<div>
  stephen
  <p id="demo">peter</p>
  ben
</div>
Grzegorz T.
  • 3,903
  • 2
  • 11
  • 24