JavaScript Text Replacement (entire page)

Discussion in 'JavaScript' started by Hyphen, Jan 25, 2009.

  1. #1
    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?
     
    Hyphen, Jan 25, 2009 IP
  2. Sleeping Troll

    Sleeping Troll Peon

    Messages:
    217
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Yes, it is possible using the DOM, (Document Object Model).
     
    Sleeping Troll, Jan 25, 2009 IP
  3. Hyphen

    Hyphen Well-Known Member

    Messages:
    464
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    110
    #3
    Can you explain? I'm just learning JavaScript.
     
    Hyphen, Jan 25, 2009 IP
  4. olddocks

    olddocks Notable Member

    Messages:
    3,275
    Likes Received:
    165
    Best Answers:
    0
    Trophy Points:
    215
  5. JDOMPer

    JDOMPer Peon

    Messages:
    11
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    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]);
    }
     
    JDOMPer, Jan 30, 2009 IP
  6. bbrez1

    bbrez1 Banned

    Messages:
    208
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #6
    <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 :)
     
    bbrez1, Jan 31, 2009 IP