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 >A/B </p>
<p >C</p>
<p >C/E</p>
I get a console error:
`Uncaught TypeError: Cannot read properties of undefined (reading 'replace')`
CodePudding user response:
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 >A/B </p>
<p >C</p>
<p >C/E</p>