Home > Articles

  • Print
  • + Share This
This chapter is from the book

Modifying Text Within a Page

You can also create a simple script to modify the contents of a heading within a web page (or any element, for that matter). As you learned earlier in this chapter, the nodeValue property of a text node contains its actual text, and the text node for a heading is a child of that heading. Thus, the syntax to change the text of a heading with the identifier head1 would be

var heading1 = document.getElementById("heading1");
heading1.firstChild.nodeValue = "New Text Here";

This assigns the heading’s object to the variable called heading1. The firstChild property returns the text node that is the only child of the heading, and its nodeValue property contains the heading text.

Using this technique, it’s easy to create a page that allows the heading to be changed dynamically. Listing 6.8 shows the complete HTML document for a script that does just that.

LISTING 6.8 The Complete Text-Modifying Example

<!DOCTYPE html>

<html lang="en">
  <head>
    <title>Dynamic Text in JavaScript</title>
    <script type="text/javascript">
    function changeTitle() {
       if (!document.getElementById) return;
       var newtitle = document.changeform.newtitle.value;
       var heading1 = document.getElementById("heading1");
       heading1.firstChild.nodeValue=newtitle;
    }
    </script>
  </head>
  <body>
    <h1 id="heading1">Dynamic Text in JavaScript</h1>
    <p>Using the W3C DOM, you can dynamically change the
    heading at the top of this page.</p>
    <p>Enter a new title and click the Change! button. </p>

    <form name="changeform">
    <input type="text" name="newtitle" size="40" />
    <button type="button" onclick="changeTitle();">Change!</button>
    </form>
  </body>
</html>

This example defines a form that enables the user to enter a new heading for the page. Clicking the button calls the changeTitle() function, defined in the <script> tag in the <head> element. This JavaScript function gets the value the user entered in the form, and it changes the heading’s value to the new text by assigning the value of the input to the heading1.firstChild.nodeValue property.

Figure 6.9 shows this page in action after a new title has been entered and the Change! button has been clicked.

FIGURE 6.9

FIGURE 6.9 The heading-modification example in action.

  • + Share This
  • 🔖 Save To Your Account