Replacing string in innerHTML

拈花ヽ惹草 提交于 2019-12-11 23:14:35

问题


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");

Thanks you for your time, Jacco


回答1:


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/



来源:https://stackoverflow.com/questions/5955823/replacing-string-in-innerhtml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!