I am trying to find a way to execute text replacement on a page that does not involve directly using 'document.write' to replace instances, but replaces all text on the page outside of the JavaScript function. For example, this script... <script type="text/javascript"> var visitorName = "Chuck"; var myOldString = "Hello username! I hope you enjoy your stay username."; var myNewString = myOldString.replace(/username/g, visitorName); document.write("Old string = " + myOldString); document.write("<br />New string = " + myNewString); </script> Code (markup): This replaces the text in the write, but if I were to then put the text string "username" outside of the </script> tag, it remains unreplaced. Is this possible?
see this: http://corpocrat.com/2008/08/10/how-to-get-selected-value-in-textarea-using-javascript/ and see how bbcode editor works (the same site) http://corpocrat.com/2008/07/30/lightweight-php-wysiwyg-html-editor/
This function will dynamically replace text in an element by id elnam is the id name of the element newtext is the "new text to be inserted" function textmod (elnam, newtext) { // get reference to the element var ttext = document.getElementById(elnam); var new_txt = document.createTextNode(newtext); ttext.replaceChild(new_txt, ttext.childNodes[0]); }
<script> function replaceText(id) { document.getElementById(id).innerHTML = "You have just clicked on the button!"; } </script> <div id="replace">You haven't clicked on the button yet!</div> <input type="button" onClick="replaceText('replace')"> This works great