Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>So, first fo all:</p> <pre><code>var code = document.getElementsByTagName('code').innerHTML; </code></pre> <p><a href="https://developer.mozilla.org/en/DOM/document.getElementsByTagName" rel="nofollow">document.getElementsByTagName</a> returns a list of <em>elements</em> not just one. So, if your purpose is escaping <em>all</em> the <code>code</code> tags you have in the page, you need to iterate them. Second, I believe you can avoid regexp just using <code>textContent</code> (where supported) or <code>innerText</code>.</p> <pre><code>var codes = document.getElementsByTagName("code"); for (var i = 0, code; code = codes[i++];) { if ("textContent" in code) code.textContent = code.innerHTML; else if ("innerText" in code) code.innerText = code.innerHTML; } </code></pre> <p>or create a new text node:</p> <pre><code>var codes = document.getElementsByTagName("code"); for (var i = 0, code, html; code = codes[i++];) { html = code.innerHTML; code.innerHTML = ""; code.appendChild(document.createTextNode(html)); } </code></pre> <p>That's should escape every html entities. If you still want to use the regexp, maybe as fallback, you can have this kind of function:</p> <pre><code>var escapeEntities = (function(){ var entities = {"&lt;" : "lt", "&gt;" : "gt", "&amp;" : "amp" }; var re = new RegExp("[" + Object.keys(entities).join("") + "]", "g"); function replaceEntities(match) { return match in entities ? "&amp;" + entities[match] + ";" : match; } return function(value) { return value.replace(re, replaceEntities); } })() </code></pre> <p>And then in your code:</p> <pre><code>code.innerHTML = escapeEntities(code.innerHTML); </code></pre> <p>Note that if <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys" rel="nofollow">Object.keys</a> is not supported you can easily use a shims (as indicated in the link); or simply replace manually the list of entities you support:</p> <pre><code> var entities = {"&lt;" : "lt", "&gt;" : "gt", "&amp;" : "amp" }; var re = /[&lt;&gt;&amp;]/g; </code></pre> <p>In that case you need to remember to add in both <code>entities</code> and <code>re</code> variables a new entity you want to support in the future; <code>Object.keys</code> just help you in maintenance.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload