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







