like it’s mentioned in the title i’m willing to replace a string inside a script tag <script>. what i want to replace is the string //WRITE by something else.
<script name="general" id="general" type="text/javascript">
some code
//Write
</script>
So i automatically tried :
ch="new string";
document.getElementById("general").replace('// WRITE',ch);
But i got the following error : Uncaught TypeError: Object #<HTMLScriptElement> has no method ‘replace’.
So i understand that unlike <div>, <script> doesn’t use that method. Is there an equivalent method ? Thanks in advance.
The object returned by “getElementById” is a DOM Element so you can change its contents by assigning to the
innerHTMLattribute:Be careful about your replacement token – your sample “script” tag uses the literal string “//Write” whereas your attempted regular expression will look for “// WRITE”, which does not exist. You must use the same literal string if you want this to work.j
[Edit] Note that scripts as defined per your example are run immediately when the browser loads the page so trying to modify them with another script will likely not have any impact. Moreover, this strategy will not work if you try to modify a script that would occur later in the page because the browser will not have loaded it so there will be no element with the target id. One possibility is to modify a function that is defined so it can be called later but this also might not work. A better strategy for including dynamic content in a JavaScript block is to have the JS itself seek information in the DOM instead of the other way around.