简体   繁体   中英

rendering xml and html tags in a code snippet HTML

simply,how to render code snippet with <html> tags like this

<div id="container">
   <div id="header_area"><tiles:insertAttribute name="header"  /></div>
   <div id="body_area"><tiles:insertAttribute name="body" /></div>
   <div id="sidebar_area"><tiles:insertAttribute name="sidebar" /></div>
   <div id="footer_area"><tiles:insertAttribute name="footer" /></div>
</div>

i found this code.but it adds endtag to all />

function encodePreElements() {
    var pre = document.getElementsByTagName('pre');
    for(var i = 0; i < pre.length; i++) {
        var encoded = htmlEncode(pre[i].innerHTML);
        pre[i].innerHTML = encoded;
    }
};

function htmlEncode(value) {
   var div = document.createElement('div');
   var text = document.createTextNode(value);
   div.appendChild(text);
   return div.innerHTML;
}

so above code will be like this

<div id="container">
    <div id="header_area"><tiles:insertattribute name="header"></tiles:insertattribute></div>
    <div id="body_area"><tiles:insertattribute name="body"></tiles:insertattribute></div>
    <div id="sidebar_area"><tiles:insertattribute name="sidebar"></tiles:insertattribute></div>
    <div id="footer_area"><tiles:insertattribute name="footer"></tiles:insertattribute></div>
</div>

.innerHTML renders correctly in javascript alert . so how can i render code snippet like first? what is the easy way to do this process?

OK, so I assume that in your question, the first quoted block is embedded inside a <pre> element, like this: <pre> <div id="container"> ... </div> </pre>

And you are trying to convert that so that it becomes: <pre> &lt;div ... </pre>

The problem is that when the page is loaded, the contents of <pre> is loaded into the DOM . When you get the value of pre[i].innerHTML , it returns you a value that accurately represents the DOM state, but is not the same as your original HTML.

If you want to preserve the exact HTML used in the page, you need to encode that HTML when you generate the page . By the time any JavaScript has access to the content, it's too late - the original HTML is gone, and all you have left is the DOM contents.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM