The insertAdjacentHTML and insertAdjacentText Methods


The insertAdjacentHTML and insertAdjacentText Methods

The insertAdjacentHTML and insertAdjacentText methods are cornerstones of Dynamic HTML; these methods enable you to insert HTML and text into a web page. You can see the support for this method in Table 6.30.

Table 6.30. The insertAdjacentHTML and insertAdjacentText Methods

Method

NS2

NS3

NS4

NS6

IE3a

IE3b

IE4

IE5

IE5.5

IE6

insertAdjacentHTML( position , HTML )

           

x

x

x

x

 

No return value

insertAdjacentText( position , text )

           

x

x

x

x

 

No return value

We'll see more about methods like this one in Chapter 16, where we change web pages on-the-fly . Both arguments that both of these methods take are strings; the position argument indicates where the HTML or text should be inserted, and the second argument holds the HTML or the text to insert. Here are the possible values for the position argument:

  • "beforeBegin" . Inserts text or HTML immediately before the object.

  • "afterBegin" . Inserts text or HTML after the start of the object (but before all other content in the object).

  • "beforeEnd" . Inserts text or HTML immediately before the end of the object (but after all other content in the object).

  • "afterEnd" . Inserts text or HTML immediately after the end of the object.

If you are inserting HTML that you want the browser to treat as HTML, use insertAdjacentHTML ; otherwise , use insertAdjacentText . (In insertAdjacentText , HTML tags are just treated as text.) Here's an example that inserts a new text field into a page when the user clicks a button:

(Listing 06-08.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Using the insertAdjacentHTML Method          </TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--             function addMore()              {  div1.insertAdjacentHTML("afterEnd",   "<P>Here is a new text field: <input type=text VALUE='Hello!'>")  }              // -->          </SCRIPT>      </HEAD>      <BODY>          <H1>Using the insertAdjacentHTML Method</H1>          <DIV ID="div1">              <INPUT TYPE=BUTTON VALUE="Click Me!" onclick="addMore()">          </DIV>      </BODY>  </HTML> 

You can see the results in Figure 6.6, where I've clicked the button a couple of times.

Figure 6.6. Using the insertAdjacentHTML Method.

graphics/06fig06.gif



Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net