I’m trying to create a Web Component, and want to be be able to access a property from the DOM.
<!doctype html>
<html lang="en-GB">
<head>
<script type="module">
class TestComponent extends HTMLElement {
constructor() {
super()
.attachShadow({mode: 'open'})
.innerHTML = '<div id="root">Test Component</div>';
}
connectedCallback() {
console.log('super');
this.value = 10;
this.setAttribute('value', '10');
}
set value (newValue) {
console.log('setValue');
this.setAttribute('value', newValue);
}
get value () {
this.getAttribute('value');
}
}
customElements.define('test-component', TestComponent);
</script>
</head>
<body>
<select id="html-select">
<option value="75">HTML Option</option>
</select>
<test-component id="test-component"></test-component>
</body>
<script>
console.log(document.getElementById('html-select').value); // outputs 75
console.log(document.getElementById('test-component').value); // outputs undefined
console.log(document.getElementById('test-component').id); // outputs 'test-component'
setTimeout(() => {
console.log(document.getElementById('test-component').value); // still outputs undefined
}, 1000);
</script>
</html>
The console log for this is:
75
test-component
undefined
super
setValue
undefined
The element attribute is correctly set on inspection, though:
<test-component id="test-component" value="10">