Reputation: 149
I need to remove the text 'at' from this title.
<p><a href="/pankcake" class="spotlight__title">Marge Makes Pancakes Email at</a></p>
The text in this title is dynamically created so I can't change the whole thing. I tried using this but it doesn't work.
<script>var elements=document.getElementsByClassName("spotlight__title");elements[0].innerHTML=elements[0].innerHTML.replace(/at/g,"");</script>
Upvotes: 0
Views: 1418
Reputation: 1132
You need to iterate over collection returned from getElementsByClassName.
var elements = document.getElementsByClassName("spotlight__title");
Array.from(elements).forEach( element =>
element.innerHTML = element.innerHTML.replace(/at/g,"")
)
Upvotes: 1
Reputation: 14257
You can use querySelectorAll
to find all elements by using a CSS Selector and then iterate over them to replace text according to your regex.
function replaceText(target, re, newText) {
document.querySelectorAll(target).forEach(function(element) {
element.textContent = element.textContent.replace(re, newText).trim();
});
}
replaceText('.spotlight__title', /at$/g, '');
<p>
<a href="/pankcake" class="spotlight__title">Marge Makes Pancakes Email 1 at</a>
</p>
<p>
<a href="/pankcake" class="spotlight__title">Marge Makes Pancakes Email 2 at</a>
</p>
<p>
<a href="/pankcake" class="spotlight__title">Marge Makes Pancakes Email 3 at</a>
</p>
Upvotes: 1