liveBook · Manning

Document Object Model

As explained in Web Components in Action

The standardized object representation of an HTML or XML document that scripts and browsers can inspect and manipulate.

The Document Object Model (DOM) is the page structure that JavaScript and the browser can inspect and change. A custom element exists as an object before it becomes part of the page’s DOM. section 4.2

A small lifecycle experiment makes the distinction clear:

  • document.createElement('my-custom-tag') creates the element and runs its constructor. section 4.2
  • Appending the element to document.body adds it to the page’s DOM and runs connectedCallback. section 4.2
  • Appending it only to a detached container does not connect it until that container enters the page’s DOM. section 4.2

Create, then connect

Use x = document.createElement('my-custom-tag') to create a custom element, then document.body.appendChild(x) to connect it and trigger its connectedCallback. section 4.2

Listing 4.1. Testing when our connectedCallback is called
<script>
   class MyCustomTag extends HTMLElement {
       connectedCallback() {
           alert('hi from MyCustomTag');                            #1
           this.innerHTML = '<h2>'+ this.getAttribute('title') +
             '</h2><button>click me</button>';
       }
   }

   if (!customElements.get('my-custom-tag')) {
       customElements.define('my-custom-tag', MyCustomTag);
   }
</script>

<style>
   my-custom-tag {
       background-color: blue;
       padding: 20px;
       display: inline-block;
       color: white;
   }
</style>

<body>
<my-custom-tag title="Another title"></my-custom-tag>
</body>

Inspect a complete custom-element example that defines a tag, renders content, and places it directly in the body. section 4.2

How Web Components in Action covers it

How deep it goes
Explains creation, attachment, detached containers, and constructor limitations, but stops short of general DOM traversal.
Examples
Uses browser-console commands, custom-element listings, detached containers, and body append operations.
What it assumes
Assumes basic JavaScript classes and inheritance while demonstrating DOM connection behavior through custom elements.
What you can do after
Apply via browser JavaScript by creating elements, inserting them, and predicting when connectedCallback runs.
How it connects
Connects the DOM with JavaScript, custom elements, HTMLElement, constructors, and connectedCallback.

Also explained in

Compare how 8 books explain Document Object Model →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.