Search code examples
javascriptcssinnerhtmlhead

How do I get identically written html?


I want to take innerHTML from style and show it in a div demo. But it should be written identically, example
I get:

#one {width: 50px; height: 50px; background-color: red; }

and I need to get;

#one{
  width: 50px;
  height: 50px;
  background-color: blue;
}

So be one below the other, with spaces, as written in notepad ++

function myFunction() {
  var x = document.getElementById("style").innerHTML
  document.getElementById("demo").innerHTML = x;
}
<head>
  <style id="style">
    #one {
      width: 50px;
      height: 50px;
      background-color: blue;
    }
  </style>
</head>

<div id="one"></div>
<div id="demo"></div>
<button onclick="myFunction()">click</button>


Solution

  • If you style the output element (demo) with the CSS white-space:pre-wrap, its content will wrap the way you need.

    From MDN:

    pre-wrap

    Sequences of white space are preserved. Lines are broken at newline characters, at <br>, and as necessary to fill line boxes.

    function myFunction(){
    var x = document.getElementById("style").innerHTML;
    document.getElementById("demo").innerHTML = x;
    }
    #demo {white-space:pre-wrap;} /* does the trick */
    <head>
    <style id="style">
    #one{
        width: 50px;
        height: 50px;
        background-color: blue;
    }
    </style>
    </head>
    <div id="one"></div>
    
    <div id="demo"></div>
    
    <button onclick="myFunction()" >click</button>