Notice the Vikings link background is Purple. The other one is Yellow.
The HTML markup for the image above was:
<h2>
The NFC North
</h2>
<a href="https://www.vikings.com/">
<color-span bgc="Purple" >
Vikings
</color-span>
</a>,
<a href="#">
<color-span>
Green Bay
</color-span>
</a>
, and others...
Observed Attributes
Web Components may use a static getter for observedAttributes(), like this:
static get observedAttributes() {
return ["bgc"];
}
Notice we define a variable named "bgc" for BackGroundColor.
The Attribute Changed CallBack
Because of the defined static getter function observedAttributes(), the WebComponent interface will call the attributeChanedCallback function when an attribute changes.
attributeChangedCallback(name, oldValue, newValue) {
this.SetStyle(name,newValue);
}
SetStyle Function
SetStyle(name, color){
let backgroundColor = "Yellow";
if(color=="Purple"){
backgroundColor="#C5B4E3";
}
this.style.textContent = `
span:hover { text-decoration: underline; color:red; }
:host(.footer) { color : #555; }
:host { background-color:${backgroundColor}; padding: 2px 5px; }
`;
}
The Color Span Web Component
class ColorSpan extends HTMLElement {
span = null;
style = null;
constructor() {
super();
this.span = document.createElement("span");
this.span.textContent = this.textContent;
this.style = document.createElement("style");
this.SetStyle();
let shadowRoot = this.attachShadow({ mode: "open" });
this.shadowRoot.appendChild(this.style);
shadowRoot.appendChild(this.span);
}
SetStyle(name, color) {
let backgroundColor = "Yellow";
if (color == "Purple") {
backgroundColor = "#C5B4E3";
}
this.style.textContent = `
span:hover { text-decoration: underline; color:red; }
:host(.footer) { color : #555; }
:host { background-color:${backgroundColor}; padding: 2px 5px; }
`;
}
static get observedAttributes() {
return ["bgc", "color"];
}
attributeChangedCallback(name, oldValue, newValue) {
this.SetStyle(name, newValue);
}
}
// Define the new element
customElements.define("color-span", ColorSpan);
The HTML Head
The script tag brings in the component from the main.js file with the defer attribute.
<head>
<meta charset="utf-8">
<title>Host selectors</title>
<script src="main.js" defer></script>
<link rel="stylesheet" href="styles.css">
</head>
Warning
Most purists would say this is a violation of concerns. And they would be right. We already have Styles, so why do this? The answer is to learn how a Web Component callback works.

SOCIAL SHARE CARD GENERATOR