Reputation: 6051
<script>
class SomeClass extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
// returns empty nodelist
console.log(this.querySelectorAll('.thing'));
}
}
customElements.define('my-component', SomeClass);
</script>
<my-component>
<div class="thing"></div>
<div class="thing"></div>
<div class="thing"></div>
</my-component>
When I try to query child elements within connectedCallback, I get an empty nodelist.
If I move script
tag after <my-component>
- it starts working:
<my-component>
<div class="thing"></div>
<div class="thing"></div>
<div class="thing"></div>
</my-component>
<script>
class SomeClass extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
// returns empty nodelist
console.log(this.querySelectorAll('.thing'));
}
}
customElements.define('my-component', SomeClass);
</script>
Is there some callback that triggers when all child elements are available? (no matter where <script>
was added). Do I really have to use something like document.ready or mutation observer? What's the most efficient way?
Upvotes: 1
Views: 370
Reputation: 87262
There appear to be a different behavior between browsers, where it works on e.g. Firefox, but Chrome (Blink) need "Mutation Observers".
Optionally one can place the script after the component, for the same reason DOM work in general.
Or make the customElements.define()
call after DOM been loaded
<script>
class SomeClass extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
// returns empty nodelist
console.log(this.querySelectorAll('.thing'));
}
}
window.addEventListener('DOMContentLoaded', function() {
customElements.define('my-component', SomeClass);
});
</script>
<my-component>
<div class="thing"></div>
<div class="thing"></div>
<div class="thing"></div>
</my-component>
Upvotes: 1