'Replace two chars in innerHTML for all elements with same class (vanilla js) [duplicate]

How can i replace two characters in multiple elements? I have found an answer using jquery but I am searching for vanilla js.

I want to replace < with &lt and > with &gt.

I tried it by myself but it only replaced first of these symbols.

let string = data.val().message;
string = string.replace("<", "&lt").replace(">", "&gt");

// <div>1</div> result was &ltdiv&gt1</div>

it only replaced the first symbols.

The element with symbols to replace has a class of .msgContent.



Solution 1:[1]

Here's how you would do it with VanillaJS using regex.

var elems = document.querySelectorAll(".class");
elems.forEach(function (elem)
{
  var msg = elem.innerHTML.replace(/</g,"&lt").replace(/>/g,"&gt");
  elem.innerHTML = msg;
  console.log(msg); // Just for illustration purpose
});
<div class="class">
  <div>Some Meessage One</div>
</div>
<div class="class">
  <div>Some Meessage Two</div>
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mosia Thabo