javascript - Replacing string in innerHTML -
so, simple thing i'm trying accomplish (javascript), it's taking me ages , still not work. i'm trying replace words (that within pre tag). example, word "static"
should replaced "<span class="keyword">static</span>"
. i'm using xhtml strict.
my approach 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 pre element, keywords array contains words replace.
i've tried many ways, i'm stuck error messages these.
firefox:
[exception... "an invalid or illegal string 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 has html tags (i've tried using %lt; , %gt; instead), because know work:
codeblock.innerhtml = codeblock.innerhtml.replace(new regexp(keywords[j], "g"), "test");
thanks time, jacco
you need wrap code in cdata
<script type="text/javascript"> //<![cdata[ (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 , javascript in xhtml documents
this way code not parsed xhtml validity.
your current code works fine me @ http://jsfiddle.net/gaby/y92ae/
Comments
Post a Comment