How to preserve raw XML / HTML and its formatting inside of a PRE-tag


Staff member
When I choose "<strong>View page source</strong>" on a certain blog post of my site, I see the correct result:

&lt;variable name="myPublicVar" type="String"&gt;
  &lt;metadata name="MemberMetaExamplePublic" /&gt;
&lt;accessor name="myAccessor" access="readwrite" type="Boolean" declaredBy="MetadataTest"&gt;
  &lt;metadata name="MemberMetaExampleGetter" /&gt;
&lt;method name="myMethod" declaredBy="MetadataTest" returnType="void"&gt;
  &lt;metadata name="MemberMetaExampleMethod" /&gt;
&lt;metadata name="CustomMeta"&gt;
  &lt;arg key="param1" value="foo" /&gt;
  &lt;arg key="param2" value="bar "/&gt;

But when I use jQuery to replace each '&lt;' and '>' to '&amp;lt;' and '&amp;gt;' respectively, the rendered result by the browser (in Chrome) messes up the self-closing elements:

&lt;variable name="myPublicVar" type="String"&gt;
  &lt;metadata name="MemberMetaExamplePublic"&gt;
&lt;accessor name="myAccessor" access="readwrite" type="Boolean" declaredby="MetadataTest"&gt;
  &lt;metadata name="MemberMetaExampleGetter"&gt;
&lt;method name="myMethod" declaredby="MetadataTest" returntype="void"&gt;
  &lt;metadata name="MemberMetaExampleMethod"&gt;
&lt;metadata name="CustomMeta"&gt;
  &lt;arg key="param1" value="foo"&gt;
  &lt;arg key="param2" value="bar "&gt;

Notice how the
elements unnecessarily generates a closing tag, and how the two
elements in the last one incorrectly generates closing tags that are actually wrapping up one
into another

The conversion I use happens in this section of jQuery / JavaScript code:

$('pre.raw').each( function(pIndex, pDIV) {
  pDIV.innerHTML = pDIV.innerHTML.replace(/\&lt;/g, "&amp;lt;").replace(/\&gt;/g, "&amp;gt;");

What could be done to stop the code from being parsed? I'm not certain whether the browser is to blame, jQuery or JavaScript?

<em>NOTE: Although I was having this problem in Wordpress and I could ask this in the
site, I think this is a generic problem that can be found in various web development scenarios.</em>