javascriptxhtmlreplaceinnerhtml

Replacing string in innerHTML using XHTML


So, this is a fairly simple thing I'm trying to accomplish (javascript), but it's taking me ages and it still does not work. I'm trying to replace certain words (that are within a pre tag). For example, the word "static" should be replaced by "<span class="keyword">static</span>". I'm using XHTML strict.

My approach is like this:

for (var j = 0; j < keywords.length; j++)
    {
        codeBlock.innerHTML = codeBlock.innerHTML.replace(new RegExp(keywords[j], "g"), "<span class=\"keyword\">" + keywords[j] + "</span>");
    }

codeBlock is the pre element, keywords is an array that contains all the words I would like to replace.

I've tried so many ways, but I'm stuck with error messages like these.

Firefox:

[Exception... "An invalid or illegal string was specified" code: "12" nsresult: "0x8053000c (NS_ERROR_DOM_SYNTAX_ERR)" location: "file:///C:/.../scripts.js Line: 33"]

Chrome:

Error: INVALID_STATE_ERR: DOM Exception 11

I'm guessing it has something to do with the html tags (I've tried using %lt; and %gt; instead), because I know that this does work:

codeBlock.innerHTML = codeBlock.innerHTML.replace(new RegExp(keywords[j], "g"), "test");


Solution

  • You will need to wrap your code in CDATA

    <script type="text/javascript">
     //<![CDATA[
    for (var j = 0; j < keywords.length; j++)
        {
            codeBlock.innerHTML = codeBlock.innerHTML.replace(new RegExp(keywords[j], "g"), "<span class=\"keyword\">" + keywords[j] + "</span>");
        }
     //]]>
    </script>
    

    Properly Using CSS and JavaScript in XHTML Documents

    This way your code will not be parsed for XHTML validity.


    Your current code works fine for me at http://jsfiddle.net/gaby/Y92AE/