replace text from string not working javascript

Viewed 38

i cant seem to get this code to work i’ve been trying at it for hours i'm trying to make a formatting system for html markup and later js and css once i can get this working the desired outcome here to to have a list of items in the var l string detect in the contenteditable <p>tag but cant get it to give me any outcome same issue when applying a filter to replace words in a string with &lt;&#47;tag&gt; i'm not sure if this is a syntax issue or just something i'm missing but i cant for the life of me find the error in my code any help is appreciated

<html>
<style>
.form {
color: green;
background: black;
}
</style>
<body>



<button onclick="register()">format</button>

<p id="demo" contenteditable>tags to format- &lt;head&gt; &lt;body&gt; &lt;html&gt; &lt;span&gt;</p>

<script>
function register() {
  let text = document.getElementById("demo").innerHTML;
  var l = ["head","body","html","span"];
  for(let i = 0; i < l.length; i++) {
  setTimeout(function() {
  document.getElementById("demo").innerHTML =
  text.replace("&lt;"+ l[i] +"&gt;","<span class='form'>&lt;"+ l[i] +"&gt;</span>");
  },500);
  }
}

</script>

</body>
</html>


1 Answers

You were overriding the innerHTML each time. Only change the innerHTML once.

function register() {
  let text = document.getElementById("demo").innerHTML;
  var l = ["head","body","html","span"];
  for(let i = 0; i < l.length; i++) {
    text =
    text.replace("&lt;"+ l[i] +"&gt;","<span class='form'>&lt;"+ l[i] +"&gt;</span>");
  }
  document.getElementById("demo").innerHTML = text;
}
.form {
color: green;
background: black;
}
<button onclick="register()">format</button>

<p id="demo" contenteditable>tags to format- &lt;head&gt; &lt;body&gt; &lt;html&gt; &lt;span&gt;</p>

Related