I am currently familiarizing myself with the concept of web components.
I am trying to give the custom component a stylesheet, so that it can mimic the page content. But the argument I am trying to pass seems to be ‘null’.
What I would expect to happen is:
- The component-style argument is succesfully received
- As a result, the webcomponent loads the intended stylesheet.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Web Component Test</title>
<script src="DiceComponent.js"></script>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<p>if it works, you shall see a webcomponent below. </p>
<p>if the webcomponent manages to use the same style as the page, it should turn green!</p>
<my-diceroll component-style="style.css"></my-diceroll>
</body>
</html>
DiceComponent.js
class DiceRoll extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({mode:'open'});
let paragraph = document.createElement("p");
paragraph.id = "dice-text";
paragraph.textContent = "GREEN when argument is passed, RED when not";
console.log(paragraph.id);
//style stuff
const style = document.createElement('link');
style.setAttribute('rel','stylesheet')
style.href = this.hasAttribute('component-style') ? this.getAttribute('component-style') : 'ComponentStyle.css';
shadow.append(paragraph);
shadow.append(style);
}
}
window.customElements.define('my-diceroll', DiceRoll);
style.css
p {
color: green;
}
ComponentStyle.css
p {
color: red;
}
current result from (chrome) browser: