开发者

Replacing string in innerHTML

开发者 https://www.devze.com 2023-03-04 18:48 出处:网络
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 exa

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"), "t开发者_如何学运维est");

Thanks you for your time, Jacco


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/

0

精彩评论

暂无评论...
验证码 换一张
取 消