This Web Components keeps the year in your copyright notice up-to-date.
export { CopyrightYearElement }
const name = "copyright-year";
class CopyrightYearElement extends HTMLSpanElement {
constructor() {
super();
}
connectedCallback() {
const year = new Date().getFullYear();
const shadow = this.attachShadow({ mode: "open" });
const span = document.createElement("span");
span.appendChild(document.createTextNode(`${this.textContent} - ${year}`));
shadow.appendChild(span);
}
}
customElements.define(name, CopyrightYearElement, {extends: 'span'});
Use the module.
<script type="module" src="copyright-year.js"></script>
Use the Web Component with the attribute is
<span>© <span is="copyright-year">2023</span> Web Component Super Hero</span>
or as a dedicated element.
<span>© <copyright-year>2023</copyright-year> Web Component Super Hero</span>
You are not exporting anything, so no export required. Its a single anonymous call.
Apple for over 10 years now has stated they will never implement
is=
syntax (extending existing elements)An Empty constructor call (only calling super()) is pointless , as each callback will call its parent callback by default; So if you do not
declare
a connectedCallback, the connectedCallback on the parent is called; I think they call it OOPthis.textContext
only works for you because the component in this case is defined after DOM is parsed.Place it in the HEAD and not in a file that loads after DOMContentLoaded and your code will fail.
::slotted()
only works on DOM elements that get slotted, not on text elements