-2

the code is very short and clear, i just want to change the color of body tag with the opening and closing tag < >

can someone explain to me why it does not work? and how to fix it.

var newColors = document.getElementById('mainPreTah').innerHTML;
newColors.replace(/<body>/g, "<span style='color:blue'><body></span>");
document.getElementById('mainPreTah').innerHTML = newColors;

1 Answers1

1

There is no need to do that. You have to traverse the DOM elements and change properties

Instead of modifiying the html you can change the DOM using the functions that already exists.

For example for this:

<body>
  <span id="myspan"></span>
</body>

You can do something like to change the color of the span.

var mySpan = document.getElementById("myspan");
mySpan.style.color = "blue";

There are multiple ways to find elements in html. You should check for those functions:

  1. getElementById
  2. getElementsByTagName
  3. getElementsByClassName
  4. getElementsByTagName
  5. getElementsByTagName

In your case, you could use

   var mySpans = document.getElementsByTagName("span"),
       i;
   for (i=0; i<mySpans.length; i++) {
       mySpans[i].style.color = "blue";
   }
Loïc Faure-Lacroix
  • 13,220
  • 6
  • 67
  • 99