JavaScript/Adding elements

DOM's Document interface offers - among other things - functions that create new elements, including their attributes and content, and joins them together or into an existing DOM.

creates an element. creates an attribute that can be assigned to this new or an already existing element. creates an attribute and links it to an existing element. integrate an element into another.

Creating elements
Now, the element and its content are created. But until here, they are not part of a DOM. They exist only in the memory of the JavaScript engine.

To integrate them into the page, we retrieve the body or any other element of an existing page and append the new element as its last element.

All in all, the HTML plus JavaScript looks like this:

The original page does not contain a paragraph. But after you click on the button, the paragraph is integrated into the page and is visible. Btw: You can click more than once on the button. What will happen?

Creating attributes
Attributes are created with either the  or the   function. The first of the two acts like the above shown  function. It creates the new attribute only in memory without a connection to other elements. Because  integrates the new attribute directly into an element, we use this variant.

The example uses the  element with its   attribute.

Now, the element, a single attribute, and the element's content are created. Again, we integrate them into the page as we have done above.

All in all, the HTML plus JavaScript looks like this:

The original page does not contain a link. But after you click on the button, the link to the IANA example page is integrated into the page and is usable.

Alternative syntax
One of the previous pages has explained how to change attributes with a different syntax.

Just use the element plus its attribute name and assign the attribute value to it. If you change the previous example to this syntax, you will reach the same behavior of adding the link.

Join the puzzles pieces
The shown functions create elements and attributes. Such new objects can be joined together to create huger parts - of course in a nested way. And they can be joined to an already existing HTML page, respectively, the DOM tree.

'Misusing' innerHTML
The content of an element can be changed by assigning a new value to its property. If this new value contains the string representation of an HTML fragment, the assignment creates child nodes within the element. That's possible but not the intended way of using.

.. leads to ..

The JavaScript fragment inserts two more paragraphs, but not behind the first one. They exist within the first one.

write
The antiquated function  was able to insert new elements into an HTML page. Its usage is strongly discouraged nowadays.

Exercises

 * ... are available on another page (click here).