javascript - Can I replace HTML text in an element by using vanilla JS as so? e.target.innerHTML.replace('old text&#

const tour = document.querySelector('.tour__heading');const addSection = e => {e.target.i

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

Can I use e.target to change HTML text as above?

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

Can I use e.target to change HTML text as above?

Share Improve this question asked Jan 31, 2020 at 2:24 petecodespetecodes 311 silver badge6 bronze badges 1
  • 3 replace doesn't change the string in-place (strings are immutable in JS). You would need to set the innerHTML equal to the return value of .replace() – Nick Parsons Commented Jan 31, 2020 at 2:25
Add a ment  | 

2 Answers 2

Reset to default 6

The String.prototype.replace function will replace the content of a string but not modify the original.

You can either do:

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

Or you can create a polyfill for a custom function on the HTMLElement object.

/* 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>


Update

A preferable approach is to avoid polluting the prototype. The optimal method for achieving this involves leveraging functional programming principles. Rather than adding a method to each DOM Element individually, a more effective strategy is to pass the Element as an argument to a function.

Here is a modern function (JSDoc included) that replaces the inner HTML of an element and returns the modified object:

/**
 * Replaces the innerHTML of a given DOM element based on a specified pattern
 * and replacement.
 *
 * @param {Element} element - The target DOM element to modify.
 * @param {String|RegExp} pattern - The search pattern to match within the
       innerHTML.
 * @param {String|Function} replacement - The string or function used for
       replacement.
 *     If a function, it receives the matched substring and should return the
 *     replacement string.
 * @return {Element} The original modified element with updated innerHTML.
 */
const replaceHTML = (element, pattern, replacement) => {
  const { innerHTML } = element;
  return Object.assign(element, {
    innerHTML: innerHTML.replace(pattern, replacement)
  });
};

document.querySelector('.click-me')
  .addEventListener('click', e => {
    replaceHTML(e.target, /\b(?:really)\b/g, 'very')
  })
.click-me:hover {
  cursor: pointer;
}
<h2 class="click-me">A really really really long title</h2>

As Nick Parson mentioned, String.replace() is a pure function. It returns a new value but doesn't mutate the existing one.

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

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


I would remend using textContent instead. Since you only want to work with text inside of an element. It's safer.


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>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745426224a4627189.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信