0

who can tell me how to deal with the innerHTML of pre in IE678 ? I know to use br, but how to do with the indentation?

My HTML:

<div id="box">
    <pre id="code">

       var a = "before";
       function b(){
           alert(a);
       }

    </pre>
</div>

My JS:

<script>
    var pre = document.getElementById("code");
    var str = pre.innerHTML;
    var newstr = str.replace("before", "after").replace(/\n/ig, "<br />");
    pre.innerHTML = newstr;
</script>

Right result in page:

var a = "after";
function b(){
    alert(a);    //note the indentation before alert 
}

Error result in page of IE678:

var a = "after"; 
function b(){ 
alert(a);        //indentation is disappeared......
}
xiaomo
  • 31
  • 1
  • 5
  • formatting code in html pages is not that easy. Maybe have a look at this http://stackoverflow.com/questions/1270221/how-to-format-code-in-html-css-js-php they mention prettyprit javascript library for this. Note that I've opened the pre tag in IE8 and ident works without having to add br. – HMR Dec 24 '12 at 02:29

1 Answers1

0

Sorry, didn't see you changing the text of the pre with JavaScript that messes it up. Here is what you can do:

    var pre = document.getElementById("code");
    var str = (pre.innerText) ? pre.innerText : pre.textContent;
    var newstr = str.replace("before", "after");//.replace(/\n/ig, "<br />");
    if(pre.textContent){pre.textContent = newstr};
    if(pre.innerText){pre.innerText = newstr};
HMR
  • 37,593
  • 24
  • 91
  • 160