I am attempting to do a quick replace of the ‘innerHTML’ of the ‘code’ element. I thought this may work:
function codeDisplay ( ) {
var code = document.getElementsByTagName('code').innerHTML;
var codeExam1 = new RegExp('<', 'gm');
var codeExam2 = new RegExp('>', 'gm');
code.replace(codeExam1, '<');
code.replace(codeExam2, '>');
}
Do I need to perform any additional steps to push the information back to the browser or conversion of data types maybe? Or am I completely wrong in how ‘RegEx’ and ‘innerHTML’ work? I appreciate the feedback in advance.
So, first fo all:
document.getElementsByTagName returns a list of elements not just one. So, if your purpose is escaping all the
codetags you have in the page, you need to iterate them.Second, I believe you can avoid regexp just using
textContent(where supported) orinnerText.or create a new text node:
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:
And then in your code:
Note that if Object.keys is not supported you can easily use a shims (as indicated in the link); or simply replace manually the list of entities you support:
In that case you need to remember to add in both
entitiesandrevariables a new entity you want to support in the future;Object.keysjust help you in maintenance.