How to Modify an HTML Text With JavaScript

JavaScript describes a web page using a standard called the Document Object Model, or DOM. The DOM assigns every element on the page to a JavaScript object, which can then be manipulated procedurally by JavaScript code. When the value of a JavaScript object corresponds to visible text on the web page, and the value is changed by a script, the page will also change to reflect the modification of the object.

Things You'll Need

  • Text or HTML editor
Show More

Instructions

    • 1

      Write the original HTML for the web page or load an existing HTML page into your text editor.

    • 2

      Identify the text you wish to change with JavaScript. Place this text in a discrete HTML tag; use "span" tags if you don't want to otherwise affect the display of the text. For example: "This text will remain the same, but <span>this text will change</span>."

    • 3

      Assign a unique ID element to the tag. For example: "This text will remain the same, but <span ID="textToChange">this text will change</span>."

    • 4

      Write a JavaScript function in the head of the HTML document to manipulate the text you wish to change. The function should read as follows:

      function ChangeText(){
      var newText = "" // add your text here, or a function to generate the text
      var textTarget = document.getElementById("textToChange")
      textTarget.firstChild.nodeValue = newText ;
      }

    • 5

      Write a JavaScript trigger in the body of the HTML document which calls the function. This could be an onChange event in a form, or an onClick event attached to a form button. You can also have the trigger occur as part of a JavaScript background script; for example, a script which runs on page load which updates a timer once per minute.

Tips & Warnings

  • View the source of HTML pages, which dynamically change text, to see the JavaScript, which makes this happen. If the JavaScript is stored in a separate page, you can load it into your browser by pasting its URL directly into your browser URL field.

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured