0

I'm trying to change the color of a special char / if it's present in any of the

tags.

This is what I have tried:

var p = document.getElementsByClassName("items");
p.innerHTML = p.innerHTML.replace(/\.|:/g, function(match) {
  return "<i style=color:tomato;font-weight:bold>" + match + "</i>"
})
<p class="i  items">A/B </p>
<p class="i  items">C</p>
<p class="i  items">C/E</p>

I get a console error:

`Uncaught TypeError: Cannot read properties of undefined (reading 'replace')`
Konrad
  • 21,590
  • 4
  • 28
  • 64
Smt
  • 13
  • 4

1 Answers1

2

getElementsByClassName returns an array-like object. Arrays don't have innerHTML property. You have to loop through all elements of that object

var ps = document.getElementsByClassName("items");
for (const p of ps) {
  p.innerHTML = p.innerHTML.replace(/\//g, function(match) {
    return "<i style=color:tomato;font-weight:bold>" + match + "</i>"
  })
}
<p class="i  items">A/B </p>
<p class="i  items">C</p>
<p class="i  items">C/E</p>
Konrad
  • 21,590
  • 4
  • 28
  • 64