简体   繁体   中英

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);

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

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>

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 recommend 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM