asp.net.ph

Skip Navigation LinksHome > Abakada: Back to Basics > Dynamic HTML > Dynamic Content

Dynamic HTML

Abakada ~ Back to Basics


Adding Content

The properties described above replace the entire contents of an element with a new string. But what if we don't want to change what is already in the document, instead only want to insert new text or HTML?

Two element methods help us do just this: insertAdjacentText and insertAdjacentHTML. These methods allow us to place new content at the beginning or end of an element, leaving the existing content intact.

insertAdjacentText

This method inserts the given text into the element at the given location. The text is inserted as plain text. Its syntax is:

object.insertAdjacentText ( location, string ) 

 Show me 

insertAdjacentHTML

This method inserts the given HTML into the element at the location. If the content includes HTML tags, the method parses and formats the text as it is inserted. Its syntax is:

object.insertAdjacentHTML ( location, string ) 

 Show me 

Both methods take two parameters: location and string.

The location parameter indicates where to insert the new content, which can be one of four possible places:

beforeBegin
Inserts the text immediately before the element.
afterBegin
Inserts the text after the start of the element but before all other content in the element.
beforeEnd
Inserts the text immediately before the end of the element but after all other content in the element.
afterEnd
Inserts the text immediately after the end of the element.

The string parameter defines the new content to insert, which can be text-only ( insertAdjacentText ), or a combination of text and HTML tags ( insertAdjacentHTML ). This must be well-formed, valid HTML or this method will fail.

Note that we cannot call any of these methods until after the document has loaded. When inserting script using the insertAdjacentHTML method, we must include the DEFER attribute in the SCRIPT tag.

For more information, please see insertAdjacentText and insertAdjacentHTML in the DHTML Methods Reference.

More ...
Back to top


© 2025 Reynald Nuñez and asp.net.ph. All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note