Styled Page Title Web Component

Show page title in Shadow DOM

by Erik Gillespie

HTML

<page-title></page-title>

<p>
  I'm a regular paragraph, unaffected by
  <code>&lt;page-title&gt;</code> styles.
</p>

CSS

body {
  background-color: #222;
  color: white;
}

JavaScript

class PageTitle extends HTMLElement {
  constructor () {
    super()
    this.attachShadow({ mode: 'open' })
    this.shadowRoot.innerHTML = `
      <style>
        :host {
          display: inline-block;
          font-family: sans-serif;
        }
        
        p {
          text-decoration: underline;
          font-weight: bold;
        }
      </style>
      <p>${document.title}</p>
    `
  }
}

customElements.define('page-title', PageTitle)