This page is a very simple demonstration of how HTML fragments (in this case, a paragraph containing some text) can be added dynamically to the current page using JavaScript and the Document Object Model (DOM). Support for the required functions is already present in DOM level 1 (1998).
Pressing the button below should add a paragraph beneath this one.
The trick is to use the DOM functions
createElement(),
createTextNode(),
and
appendChild(),
as the (simplified) code below demonstrates.
// Get the section to add the paragraph to: var Section = document.getElementById("Section"); // Create a new paragraph node: var P = document.createElement("P"); // Create a new text node: var Text = document.createTextNode("The new paragraph's contents."); // Add the text to the paragraph: P.appendChild(Text); // Append the paragraph to the section: Section.appendChild(P);
For further reading, the DOM level 1 and DOM level 2 Core specifications are worthwhile.
Tested to work on the following browsers:
Does not work on the following browsers:
Check HTML - Check CSS - Index