In Ajax, you frequently want to update just part of a Web page, not the whole page. Two methods enable you to do this: the insertAdjacentHTML method, which lets you insert HTML next to an element that already exists, and the insertAdjacentText method, which lets you insert text in the same way. You can determine where the new text or HTML will go with respect to the already existing element by passing the constants BeforeBegin, AfterBegin, BeforeEnd, or AfterEnd to insertAdjacentHTML and insertAdjacentText.
The example insertAdjacent.html uses the insertAdjacentHTML method. This page starts with just a button, as shown in Figure 11.13. When you click the button, the code inserts a new text field into the Web page, as shown in Figure 11.14.
Figure 11.13: The insertAdjacent.html application
Figure 11.14: Inserting a new text field into a page
Here’s how it works: the application contains a <div> element with the ID div1:
<body> <center> <h1> Updating part of a page </h1> </center> <div > . . . </div> </body>
and that <div> element contains the button, which is connected to a JavaScript function named
update: <body> <center> <h1> Updating part of a page </h1> </center> <div > <input type=button value="Click Me!" onclick="update()"> </div> </body>
In the update function, you can call the <div> element’s insertAdjacentHTML method to insert the text field next to the <div> element:
<head> <title> Updating part of a page </title> <script language="JavaScript"> function update() { div1.insertAdjacentHTML(...); } </script> </head>
Here’s how you insert the new text field after the end of the <div> element:
<head> <title> Updating part of a page </title> <script language="JavaScript"> function update() { div1.insertAdjacentHTML("AfterEnd", "<p>Here's A new text field: <input type=text value='Hello!'></p>"); } </script> </head>
Using insertAdjacentHTML and insertAdjacentText, you can insert HTML and text into a Web page, adjacent to another Web page item. In fact, there’s another way to insert text and HTML into a Web page besides using these methods: you can use dynamic HTML properties, which gives you even finer control than the insertAdjacentHTML and insertAdjacentText methods.