Home > database >  HTML only replaces 1st match
HTML only replaces 1st match

Time:04-11

How can I make that this code replaces both paragraphs? I also need it to work with lists.

<p >Mr Blue has a blue house and a blue car blue blu,e blue bl,ue.</p>
<p >Mr Blue has a blue house and a blue car blu,e blue bl,ue blue.</p>

<script>
let str = document.getElementByClass("demo").innerHTML; 
let res = str.replace(/,/g, ", ");
document.getElementByClass("demo").innerHTML = res;
</script>

CodePudding user response:

Never refer by ID, always use classes.

var els = document.getElementsByClassName('kala');
for (var i = 0; i < els.length; i  ) {
  els[i].innerHTML = els[i].innerHTML.replace(/,/g, ', ');
}

This kind of a snippet does the job!

CodePudding user response:

You can't use 2 (or more) ids which are equals. Instead of use class:

<p >Mr Blue has a blue house and a blue car blue blue blue blue.</p>
<p >Mr Blue has a blue house and a blue car blue blue blue blue.</p>

//

const elements = document.querySelectorAll(".demo"); 

elements.forEach((element) => element.textContent.replace(/blue/g, "red"));

  • Related