I want to create new element and append into #container
section on connectedCallback
. I use this.shadowRoot.querySelector("#container")
to select the element, but it always returns null
. How can I select the element in the shadow root?
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://polygit.org/components/webcomponentsjs/webcomponents-loader.js"></script>
<link rel="import" href="https://polygit.org/components/polymer/polymer-element.html">
</head>
<body>
<dom-module id="dom-element">
<template>
<div id="container">
<p>I'm a DOM element. This is my shadow DOM!</p>
</div>
</template>
<script>
class DomElement extends Polymer.Element {
connectedCallback() {
this.attachShadow({
mode: "open"
})
console.log(this.shadowRoot.querySelector("#container"))
}
static get is() {
return "dom-element";
}
}
customElements.define(DomElement.is, DomElement);
</script>
</dom-module>
<dom-element></dom-element>
</body>
</html>
The Polymer.Element
already attaches a shadow root, so you don't need to do that yourself in connectedCallback()
. More importantly, your custom connectedCallback()
must call super.connectedCallback()
for proper operation. It should look something like this:
connectedCallback() {
super.connectedCallback(); // DO THIS
// this.attachShadow(...) // DON'T DO THIS
console.log('container', this.shadowRoot.querySelector("#container"));
}