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=".js"></script>
<link rel="import" href=".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>
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/ponents/webponentsjs/webponents-loader.js"></script>
<link rel="import" href="https://polygit/ponents/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>
Share
Improve this question
edited May 27, 2017 at 6:27
tony19
139k23 gold badges277 silver badges347 bronze badges
asked May 27, 2017 at 1:07
G.C SunG.C Sun
331 silver badge5 bronze badges
1 Answer
Reset to default 5The 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"));
}
demo
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742383546a4433598.html
评论列表(0条)