Reputation: 33
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')`
Upvotes: 0
Views: 29
Reputation: 24661
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>
Upvotes: 2