JavaScript/Adding elements

From Wikibooks, open books for an open world
Jump to navigation Jump to search




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.

createElement() creates an element. createAttribute() creates an attribute that can be assigned to this new or an already existing element. setAttribute() creates an attribute and links it to an existing element. appendChild() integrate an element into another.

Creating elements[edit | edit source]

// an <p> element
const p = document.createElement("p");
// its content
p.innerHTML = "The new paragraph.";

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.

const body = document.getElementById("body");
body.appendChild(p);

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

<!DOCTYPE html>
<html>
<head>
  <script>
    function show() {
      "use strict";

      // an create an <p> element
      const p = document.createElement("p");
      // create its content
      p.innerHTML = "The new paragraph.";

      // integrate it into the body
      const body = document.getElementById("body");
      body.appendChild(p);
    }
  </script>
</head>

<body id="body" style="margin:2em">
  <button id="buttonShow" onclick="show()">Start</button>
</body>
</html>

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[edit | edit source]

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

The example uses the a element with its href attribute.

// an <a> element
const anchor = document.createElement("a");
// its content
anchor.innerHTML = "The IANA example daomain.";
// its 'href' attribute
anchor.setAttribute("href", "https://www.example.com");

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:

<!DOCTYPE html>
<html>
<head>
  <script>
    function show() {
      "use strict";

      // an create an <a> element
      const anchor = document.createElement("a");
      // create its content
      anchor.innerHTML = "The IANA example domain.";
      // create its 'href' attribute
      anchor.setAttribute("href", "https://www.example.com");
        // see below: anchor.href = "https://www.example.com";

      // integrate the element inclusive its attribute into the body
      const body = document.getElementById("body");
      body.appendChild(anchor);
      /* now, the body looks like this:
        <button id="buttonShow" onclick="show()">Start</button>
        <a href="https://www.example.com">The IANA example domain.</a>
      */
    }
  </script>
</head>

<body id="body" style="margin:2em">
  <button id="buttonShow" onclick="show()">Start</button>
</body>
</html>

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[edit | edit source]

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

element_name.attribute_name = "new value";

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.

  anchor.href = "https://www.example.com";
  // instead of the above:
  // anchor.setAttribute("href", "https://www.example.com");

Join the puzzles pieces[edit | edit source]

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.

const div = document.getElementById("div_1");
const anchor = document.createElement("a");
div.appendChild(anchor);

'Misusing' innerHTML[edit | edit source]

The content of an element can be changed by assigning a new value to its property innerHTML. 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 innerHTML.

const elem = document.getElementById("p1");
elem.innerHTML = "New text in the paragraph.<p>next P</p><p>and even one more P</p>";

.. leads to ..

<p id="p1">New text in the paragraph
  <p>next P</p>
  <p>and even one more P</p>
</p>

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

write()[edit | edit source]

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

See also[edit | edit source]

Exercises[edit | edit source]

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