我可以这样使用 vanilla JS 替换元素中的 HTML 文本吗? e.target.innerHTML.replace('old text', 'new text');

Can I replace HTML text in an element by using vanilla JS as so? e.target.innerHTML.replace('old text', 'new text');

const tour = document.querySelector('.tour__heading');
const addSection = e => {
        e.target.innerHTML.replace('SHOW','red');
};
tour.addEventListener('click', addSection);

我可以使用 e.target 来更改上面的 HTML 文本吗?

String.prototype.replace函数会替换字符串的内容,但不会修改原来的内容。

您可以:

e.target.innerHTML = e.target.innerHTML.replace('SHOW','red')

或者您可以为 HTMLElement 对象上的自定义函数创建一个 polyfill。

/* A polyfill for a custom HTML text replacer function */
if (HTMLElement.prototype.replaceHTML === undefined) {
  HTMLElement.prototype.replaceHTML = function(regexpOrSubstr, newSubstrOrFunc) {
    this.innerHTML = this.innerHTML.replace.apply(this.innerHTML, arguments)
  }
}

const tour = document.querySelector('.tour__heading')
const addSection = e => {
  //e.target.innerHTML = e.target.innerHTML.replace('SHOW','red')
  e.target.replaceHTML('SHOW','red')
}
tour.addEventListener('click', addSection)
.tour__heading:hover {
  cursor: pointer;
}
<div class="tour__heading">SHOW</div>

Nick Parson所述,String.replace()是一个纯函数。它 returns 一个新值但不会改变现有值。

const initialText = 'initial';
const changedText = initialText.replace('initial', 'changed');

console.log(changedText);
console.log(initialText);


我建议改用 textContent。因为您只想处理元素内的文本。更安全。


const tour = document.querySelector('.tour__heading');
const addSection = e => {
        const text = e.target.textContent;
        const updatedText = text.replace('SHOW','red');
        e.target.textContent = updatedText;
};
tour.addEventListener('click', addSection);
<h1 class="tour__heading">
  SHOW
</h1>