I just spent many minutes trying to debug this issue. I found no source documenting this behavior ― maybe I missed them if they do exist ― and I decided to write this here in case someone else faces the same issue.
A Web Component I built has a <slot>
element with a default <div>
inside of it:
<slot name="timer">
<div class="rp__timer"></div>
</slot>
When I tried to update the <div>
using innerHTML
nothing happened. It is as if the <div>
doesn't exist. Here's how I tried to access the <div>
:
this.timerSlot = this.shadowRoot.querySelector('slot[name=timer]');
let div = this.timerSlot.assignedNodes({flatten: true})[0];
div.innerHTML = "SOME TEXTE";
But nothing is happening. What's wrong with this code?
DOM nodes are not the same as DOM elements
<p>Hello<a href="...">Web Components</a>World</p>
Elements p and a are a sub-set of all Nodes
So assignedNodes gives you all 5 Nodes (href
in the image is an attribute)
and assignedElements gives you the 2 Elements you are after
For documentation always use MDN (although MDN isn't 100% correct either)