Iterate over HTMLCollection in custom element - javascript

How can I iterate over instances of one custom element within the shadow dom of another custom element? HTMLCollections don't seem to behave as expected. (I'm a jQuerian and a novice when it comes to vanilla js, so I'm sure I'm making an obvious error somewhere).
HTML
<spk-root>
<spk-input></spk-input>
<spk-input></spk-input>
</spk-root>
Custom Element Definitions
For spk-input:
class SpektacularInput extends HTMLElement {
constructor() {
super();
}
}
window.customElements.define('spk-input', SpektacularInput);
For spk-root:
let template = document.createElement('template');
template.innerHTML = `
<canvas id='spektacular'></canvas>
<slot></slot>
`;
class SpektacularRoot extends HTMLElement {
constructor() {
super();
let shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.appendChild(template.content.cloneNode(true));
}
update() {
let inputs = this.getElementsByTagName('spk-input')
}
connectedCallback() {
this.update();
}
}
window.customElements.define('spk-root', SpektacularRoot);
Here's the part I don't understand. Inside the update() method:
console.log(inputs) returns an HTMLCollection:
console.log(inputs)
// output
HTMLCollection []
0: spk-input
1: spk-input
length: 2
__proto__: HTMLCollection
However, the HTMLCollection is not iterable using a for loop, because it has no length.
console.log(inputs.length)
// output
0
Searching SO revealed that HTMLCollections are array-like, but not arrays. Trying to make it an array using Array.from(inputs) or the spread operator results in an empty array.
What's going on here? How can I iterate over the spk-input elements within spk-root from the update() method?
I'm using gulp-babel and gulp-concat and using Chrome. Let me know if more info is needed. Thanks in advance.
Edit: To clarify, calling console.log(inputs.length) from within the update() outputs 0 instead of 2.

The reason will be that connectedCallback() of a custom element in certain cases will be called as soon as the browser meets the opening tag of the custom element, with children not being parsed, and thus, unavailable. This does e.g. happen in Chrome if you define the elements up front and the browser then parses the HTML.
That is why let inputs = this.getElementsByTagName('spk-input') in your update() method of the outer <spk-root> cannot find any elements. Don't let yourself be fooled by misleading console.log output there.
I've just recently taken a deep dive into this topic, and suggested a solution using a HTMLBaseElement class:
https://gist.github.com/franktopel/5d760330a936e32644660774ccba58a7
Andrea Giammarchi (the author of document-register-element polyfill for custom elements in non-supporting browsers) has taken on that solution suggestion and created an npm package from it:
https://github.com/WebReflection/html-parsed-element
As long as you don't need dynamic creation of your custom elements, the easiest and most reliable fix is to create the upgrade scenario by putting your element defining scripts at the end of the body.
If you're interested in the discussion on the topic (long read!):
https://github.com/w3c/webcomponents/issues/551
Here's the full gist:
HTMLBaseElement class solving the problem of connectedCallback being called before children are parsed
There is a huge practical problem with web components spec v1:
In certain cases connectedCallback is being called when the element's child nodes are not yet available.
This makes web components dysfunctional in those cases where they rely on their children for setup.
See https://github.com/w3c/webcomponents/issues/551 for reference.
To solve this, we have created a HTMLBaseElement class in our team which serves as the new class to extend autonomous custom elements from.
HTMLBaseElement in turn inherits from HTMLElement (which autonomous custom elements must derive from at some point in their prototype chain).
HTMLBaseElement adds two things:
a setup method that takes care of the correct timing (that is, makes sure child nodes are accessible) and then calls childrenAvailableCallback() on the component instance.
a parsed Boolean property which defaults to false and is meant to be set to true when the components initial setup is done. This is meant to serve as a guard to make sure e.g. child event listeners are never attached more than once.
HTMLBaseElement
class HTMLBaseElement extends HTMLElement {
constructor(...args) {
const self = super(...args)
self.parsed = false // guard to make it easy to do certain stuff only once
self.parentNodes = []
return self
}
setup() {
// collect the parentNodes
let el = this;
while (el.parentNode) {
el = el.parentNode
this.parentNodes.push(el)
}
// check if the parser has already passed the end tag of the component
// in which case this element, or one of its parents, should have a nextSibling
// if not (no whitespace at all between tags and no nextElementSiblings either)
// resort to DOMContentLoaded or load having triggered
if ([this, ...this.parentNodes].some(el=> el.nextSibling) || document.readyState !== 'loading') {
this.childrenAvailableCallback();
} else {
this.mutationObserver = new MutationObserver(() => {
if ([this, ...this.parentNodes].some(el=> el.nextSibling) || document.readyState !== 'loading') {
this.childrenAvailableCallback()
this.mutationObserver.disconnect()
}
});
this.mutationObserver.observe(this, {childList: true});
}
}
}
Example component extending the above:
class MyComponent extends HTMLBaseElement {
constructor(...args) {
const self = super(...args)
return self
}
connectedCallback() {
// when connectedCallback has fired, call super.setup()
// which will determine when it is safe to call childrenAvailableCallback()
super.setup()
}
childrenAvailableCallback() {
// this is where you do your setup that relies on child access
console.log(this.innerHTML)
// when setup is done, make this information accessible to the element
this.parsed = true
// this is useful e.g. to only ever attach event listeners once
// to child element nodes using this as a guard
}
}

The HTMLCollection inputs does have a length property, and if you log it inside the update function you will see it's value is 2. You can also iterate through the inputs collection in a for loop so long as it's inside the update() function.
If you want to access the values in a loop outside of the update function, you can store the HTMLCollection in a variable declared outside of the scope of the SpektacularInput class.
I suppose there are other ways to store the values depending on what you're trying to accomplish, but hopefully this answers your initial question "How can I iterate over the spk-input elements within spk-root from the update() method?"
class SpektacularInput extends HTMLElement {
constructor() {
super();
}
}
window.customElements.define('spk-input', SpektacularInput);
let template = document.createElement('template');
template.innerHTML = `
<canvas id='spektacular'></canvas>
<slot></slot>
`;
// declare outside variable
let inputsObj = {};
class SpektacularRoot extends HTMLElement {
constructor() {
super();
let shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.appendChild(template.content.cloneNode(true));
}
update() {
// store on outside variable
inputsObj = this.getElementsByTagName('spk-input');
// use in the function
let inputs = this.getElementsByTagName('spk-input');
console.log("inside length: " + inputs.length)
for(let i = 0; i < inputs.length; i++){
console.log("inside input " + i + ": " + inputs[i]);
}
}
connectedCallback() {
this.update();
}
}
window.customElements.define('spk-root', SpektacularRoot);
console.log("outside length: " + inputsObj.length);
for(let i = 0; i < inputsObj.length; i++){
console.log("outside input " + i + ": " + inputsObj[i]);
}
<spk-root>
<spk-input></spk-input>
<spk-input></spk-input>
</spk-root>
Hope it helps,
Cheers!

Related

How to properly handle Javascript custom element (Web Component) with children elements?

I have a Custom Element that should have many HTML children. I had this problem when initializing it in class' constructor (The result must not have children). I understand why and know how to fix it. But exactly how I should design my class around it now? Please consider this code:
class MyElement extends HTMLElement {
constructor() {
super();
}
// Due to the problem, these codes that should be in constructor are moved here
connectedCallback() {
// Should have check for first time connection as well but ommited here for brevity
this.innerHTML = `<a></a><div></div>`;
this.a = this.querySelector("a");
this.div = this.querySelector("div");
}
set myText(v) {
this.a.textContent = v;
}
set url(v) {
this.a.href = v;
}
}
customElements.define("my-el", MyElement);
const frag = new DocumentFragment();
const el = document.createElement("my-el");
frag.append(el); // connectedCallback is not called yet since it's not technically connected to the document.
el.myText = "abc"; // Now this wouldn't work because connectedCallback isn't called
el.url = "https://www.example.com/";
Since MyElement would be used in a list, it's set up beforehand and inserted into a DocumentFragment. How do you handle this?
Currently I am keeping a list of pre-connected properties and set them when it's actually connected but I can't imagine this to be a good solution. I also thought of another solution: have an init method (well I just realized nothing prevents you from invoking connectedCallback yourself) that must be manually called before doing anything but I myself haven't seen any component that needs to do that and it's similar to the upgrade weakness mentioned in the above article:
The element's attributes and children must not be inspected, as in the non-upgrade case none will be present, and relying on upgrades makes the element less usable.
Custom elements are tricky to work with.
The shadowDOM
if the shadowDOM features and restrictions suits your needs, you should go for it, it's straightforward :
customElements.define('my-test', class extends HTMLElement{
constructor(){
super();
this.shadow = this.attachShadow({mode: 'open'});
const div = document.createElement('div');
div.innerText = "Youhou";
this.shadow.appendChild(div);
}
});
const myTest = document.createElement('my-test');
console.log(myTest.shadow.querySelector('div')); //Outputs your div.
More about it there
Without shadowDOM
Sometimes, the shadowDOM is too restrictive. It provides a really great isolation, but if your components are designed to be used in an application and not be distributed to everyone to be used in any project, it can really be a nightmare to manage.
Keep in mind that the solution I provide below is just an idea of how to solve this problem, you may want to manage much more than that, especialy if you work with attributeChangedCallback, if you need to support component reloading or many other use cases not covered by this answer.
If, like me, you don't want the ShadowDOM features, and there is many reasons not to want it (cascading CSS, using a library like fontawesome without having to redeclare the link in every component, global i18n mechanism, being able to use a custom component as any other DOM tag, and so on), there is some clue :
Create a base class that will handle it in the same way for all components, let's call it BaseWebComponent.
class BaseWebComponent extends HTMLElement{
//Will store the ready promise, since we want to always return
//the same
#ready = null;
constructor(){
super();
}
//Must be overwritten in child class to create the dom, read/write attributes, etc.
async init(){
throw new Error('Must be implemented !');
}
//Will call the init method and await for it to resolve before resolving itself.
//Always return the same promise, so several part of the code can
//call it safely
async ready(){
//We don't want to call init more that one time
//and we want every call to ready() to return the same promise.
if(this.#ready) return this.#ready
this.#ready = new Promise(resolve => resolve(this.init()));
return this.#ready;
}
connectedCallback(){
//Will init the component automatically when attached to the DOM
//Note that you can also call ready to init your component before
//if you need to, every subsequent call will just resolve immediately.
this.ready();
}
}
Then I create a new component :
class MyComponent extends BaseWebComponent{
async init(){
this.setAttribute('something', '54');
const div = document.createElement('div');
div.innerText = 'Initialized !';
this.appendChild(div);
}
}
customElements.define('my-component', MyComponent);
/* somewhere in a javascript file/tag */
customElements.whenDefined('my-component').then(async () => {
const component = document.createElement('my-component');
//Optional : if you need it to be ready before doing something, let's go
await component.ready();
console.log("attribute value : ", component.getAttribute('something'));
//otherwise, just append it
document.body.appendChild(component);
});
I do not know any approach, without shdowDOM, to init a component in a spec compliant way that do not imply to automaticaly call a method.
You should be able to call this.ready() in the constructor instead of connectedCallback, since it's async, document.createElement should create your component before your init function starts to populate it. But it can be error prone, and you must await that promise to resolve anyway to execute code that needs your component to be initialized.
You need (a) DOM to assign content to it
customElements.define("my-el", class extends HTMLElement {
constructor() {
super().attachShadow({mode:"open"}).innerHTML=`<a></a>`;
this.a = this.shadowRoot.querySelector("a");
}
set myText(v) {
this.a.textContent = v;
}
});
const frag = new DocumentFragment();
const el = document.createElement("my-el");
frag.append(el);
el.myText = "abc";
document.body.append(frag);
Without shadowDOM you could store the content and process it in the connectedCallback
customElements.define("my-el", class extends HTMLElement {
constructor() {
super().atext = "";
}
connectedCallback() {
console.log("connected");
this.innerHTML = `<a>${this.atext}</a>`;
this.onclick = () => this.myText = "XYZ";
}
set myText(v) {
if (this.isConnected) {
console.warn("writing",v);
this.querySelector("a").textContent = v;
} else {
console.warn("storing value!", v);
this.atext = v;
}
}
});
const frag = new DocumentFragment();
const el = document.createElement("my-el");
frag.append(el);
el.myText = "abc";
document.body.append(frag);
Since there are many great answers, I am moving my approach into a separate answer here. I tried to use "hanging DOM" like this:
class MyElement extends HTMLElement {
constructor() {
super();
const tmp = this.tmp = document.createElement("div"); // Note in a few cases, div wouldn't work
this.tmp.innerHTML = `<a></a><div></div>`;
this.a = tmp.querySelector("a");
this.div = tmp.querySelector("div");
}
connectedCallback() {
// Should have check for first time connection as well but ommited here for brevity
// Beside attaching tmp as direct descendant, we can also move all its children
this.append(this.tmp);
}
set myText(v) {
this.a.textContent = v;
}
set url(v) {
this.a.href = v;
}
}
customElements.define("my-el", MyElement);
const frag = new DocumentFragment();
const el = document.createElement("my-el");
frag.append(el); // connectedCallback is not called yet since it's not technically connected to the document.
el.myText = "abc"; // Now this wouldn't work because connectedCallback isn't called
el.url = "https://www.example.com/";
document.body.append(frag);
It "works" although it "upsets" my code a lot, for example, instead of this.querySelector which is more natural, it becomes tmp.querySelector. Same in methods, if you do a querySelector, you have to make sure tmp is pointing to the correct Element that the children are in. I have to admit this is probably the best solution so far.
I'm not exactly sure about what makes your component so problematic, so I'm just adding what I would do:
class MyElement extends HTMLElement {
#a = document.createElement('a');
#div = document.createElement('div');
constructor() {
super().attachShadow({mode:'open'}).append(this.#a, this.#div);
console.log(this.shadowRoot.innerHTML);
}
set myText(v) { this.#a.textContent = v; }
set url(v) { this.#a.href = v; }
}
customElements.define("my-el", MyElement);
const frag = new DocumentFragment();
const el = document.createElement("my-el");
el.myText = 'foo'; el.url= 'https://www.example.com/';
frag.append(el);
document.body.append(el);

Custom properties on Custom Elements

After a custom element has been parsed and added to the DOM, can I get access to a custom property I created at the constructor time, like:
const props = []
return new CustomElement(props)
// later in code
class CustomElement {
...
constructor(props) {
this.customProperty = props
}
toString() {
return this.outerHTML
}
...
}
// later in code
const ce = document.querySelector("custom-element")
console.log( ce.customProperty ) // []
Yes, no different than regular DOM elements.
And with document.createElement("custom-element") your property is there too.
Note with the latter only the constructor was executed.
So props you add in the connectedCallback won't be set yet.
For these type of questions try your own code in a JSFiddle or CodePen or https://webcomponents.dev

custom elements & connectedCallback() : wait for parent node to be available before firing a function

I'm using custom elements, which are very nice.
But I'm facing a problem :
When the connectedCallback() function is called, it seems that the node is not yet at its place in the DOM, thus I cannot access its parents - and I need them.
class myElement extends HTMLElement{
constructor() {
super();
this.tracklist = undefined;
}
connectedCallback(){
this.render();
}
render(){
this.tracklist = this.closest('section');
// following code requires this.tracklist!
// ...
}
window.customElements.define('my-element', myElement);
How could I be sure the parent nodes are accessible before calling render() ?
Thanks !
It is a known issue:
connectedCallback does not mean your element is or is not fully parsed.
Custom Elements is lacking a parsedCallback method
See all the answers at:
textContent empty in connectedCallback() of a custom HTMLElement
connectedcallback-of-a-custom-htmlelement
How to have a 'connectedCallback' for when all child custom elements have been connected
TL;DR;
The accepted method is to delay your render method:
connectedCallback(){
setTimeout(this.render);
}
It seems that the connectedCallback cannot access other elements in relation to itself when it hasn't been parsed yet. This kind of makes sense if you consider that a custom-element has to be able to live anywhere in the DOM without being dependent on another element. So if there were no parent to be selected, the element would probably not work properly.
A way to do this is to modify the render method to take an argument which will set the tracklist property dynamically to the custom element. Then select the my-element element from the DOM and look for the section.
Then use the customElements.whenDefined method to connect the section and my-element together whenever the custom element is ready. This method returns a Promise that resolves whenever the custom element is defined and gives you the ability to execute a callback.
See example below:
// Do something whenever the element is ready.
window.addEventListener('load', function() {
// Wait for the document to load so the DOM has been parsed.
window.customElements.whenDefined('my-element').then(() => {
const myElement = document.querySelector('my-element');
// Only do something if the element exists on the page.
if (myElement !== null) {
const tracklist = myElement.closest('section');
myElement.render(tracklist);
console.log(myElement.tracklist);
}
});
});
// Create element.
class myElement extends HTMLElement{
constructor() {
super();
this.tracklist = null;
}
render(tracklist){
this.tracklist = tracklist;
// following code requires this.tracklist!
// ...
}
}
// Define element.
window.customElements.define('my-element', myElement);
<section>
<my-element></my-element>
</section>
If I have been unclear or you have questions, please let me know.
Have a nice day!
I haven't tested this out but seems like a Promise might work:
// DomReady.js
class DomReady extends HTMLElement {
constructor() {
super();
this.domReadyPromise = new Promise(resolve => (this.domReadyResolve = resolve));
}
connectedCallback() {
this.domReadyResolve();
}
domReady() { return this.domReadyPromise; }
}
// ParentCustom.js
class ParentCustom extends DomReady {
connectedCallback() {
super.connectedCallback();
...
}
}
// ChildCustom.js
class ChildCustom extends HTMLElement {
async connectedCallback() {
await document.querySelector('parent-custom').domReady();
}
}

Initialisation of Custom Elements Inside Document Fragment

Consider this HTML template with two flat x-elements and one nested.
<template id="fooTemplate">
<x-element>Enter your text node here.</x-element>
<x-element>
<x-element>Hello, World?</x-element>
</x-element>
</template>
How to initialise (fire constructor) all custom elements in cloned from fooTemplate document fragment without appending it to DOM, neither by extending built-in elements with is="x-element"; either entire fragment.
class XElement extends HTMLElement {
constructor() { super(); }
foo() { console.log( this ); }
} customElements.define( 'x-element', XElement );
const uselessf = function( temp ) {
const frag = window[ temp ].content.cloneNode( true );
/* Your magic code goes here:
*/ do_black_magic( frag );
for (const e of frag.querySelectorAll('x-element') )
e.foo(); // This should work.
return frag;
};
window['someNode'].appendChild( uselessf('fooTemplate') );
Note that script executes with defer attribute.
We can initialise template with this arrow function:
const initTemplate = temp =>
document.createRange().createContextualFragment( temp.innerHTML );
const frag = initTemplate( window['someTemplate'] );
Or with this method defined on template prototype (I prefer this way):
Object.defineProperty(HTMLTemplateElement.prototype, 'initialise', {
enumerable: false,
value() {
return document.createRange().createContextualFragment( this.innerHTML );
}
});
const frag = window['someTemplate'].initialise();
In any case in result this code will work fine:
for (const elem of frag.querySelectorAll('x-element') )
elem.foo();
window['someNode'].appendChild( frag );
I'm not sure if these methods are the most effective way to initialise custom elements in template.
Also note that there is no need for cloning template.
TLDR:
Use document.importNode(template.content, true); instead of template.content.cloneNode(true);
Read more about document.importNode() here.
Explanation:
Since the custom element is created in a different document/context (the DocumentFragment of the template) it doesn't know about the custom elements definition in the root/global document. You can get the document an element belongs to by reading the Node.ownerDocument property (MDN) which in this case will be different to the window.document element.
This being said you need to create the custom element in the context of the global document in order to "apply" the custom element. This can be done by calling document.importNode(node, [true]) (MDN) which works like node.cloneNode([true]), but creates a copy of the element in the global document context.
Alternatively you can also use document.adoptNode(node) (MDN) to first adopt the DocumentFragment to the global document and then create copies of it via node.cloneNode([true]). Note though if you use adoptNode() on an HTML element it will be removed from its original document.
Illustrative Example Code:
class XElement extends HTMLElement {
constructor() { super(); console.log("Custom Element Constructed") }
}
customElements.define( 'x-element', XElement );
const externalFragment = fooTemplate.content;
console.log(
"Is ownerDocument equal?",
externalFragment.ownerDocument === document
);
console.log("import start");
const importedFragment = document.importNode(externalFragment, true);
console.log("import end");
console.log(
"Is ownerDocument equal?",
importedFragment.ownerDocument === document
);
<template id="fooTemplate">
<x-element>Hello, World?</x-element>
</template>
Note: Appending an element from one document to another document forces an implicit adoption of the node. That's why appending the element to the global DOM works in this case.
You can avoid the "createContextualFragment" hack from the previous answer by simply adding the template clone to the document immediately before processing it.
Assuming we have these two variables defined...
const containerEl = document.querySelector('div.my-container')
const templateEl = document.querySelector('#fooTemplate')
...instead of doing this (where frag contains uninitialised custom elements)...
const frag = templateEl.content.cloneNode(true)
manipulateTemplateContent(frag)
containerEl.appendChild(frag)
...append the template clone to the document first, then manipulate it. The user won't notice any difference - it's all synchronous code executed within the same frame.
const frag = templateEl.content.cloneNode(true)
containerEl.appendChild(frag)
manipulateTemplateContent(containerEl)

Accessing childNodes of custom elments?

This might be a bit confusing. I am trying to access innerHTML or childNodes from my custom element. Is it possible to get access to the original DOM structure from the web component import file? BEFORE attachShadow?
In the below example I am trying to get access to the src of the two jookah-images from my jookah-gallery import file.
Disclaimer: Im a total noob when it comes to shadow DOM and web components so if there are any major mistakes I'd love to understand why. Thanks for any help!
index.html
<jookah-gallery>
//here
<jookah-image class="gallery-image" src="http://merehead.com/blog/wp-content/uploads/gradient-design.jpeg">
<jookah-image class="gallery-image" src="https://webgradients.com/public/webgradients_png/035%20Itmeo%20Branding.png">
</jookah-gallery>
import file for jookah-gallery:
(function(owner) {
class jookahGallery extends HTMLElement {
constructor() {
super();
//this returns false
if (this.hasChildNodes()) {
console.log('there are nodes')
}else{
console.log('NO nodes')
}
//shadow DOM attach
const shadowRoot = this.attachShadow({mode: 'open'});
const template = owner.querySelector('#jookah-gallery-template');
const instance = template.content.cloneNode(true);
shadowRoot.appendChild(instance);
}
// ---------------- object events -------------------------//
connectedCallback() {
}
render(){
}
disconnectedCallback(){
}
attributeChangedCallback(){
}
// ---------------- methods ------------------------//
}
customElements.define('jookah-gallery', jookahGallery);
})(document.currentScript.ownerDocument);
According to the Spec you are not supposed to inspect, change, add and children in the constructor of your Web Component.
https://w3c.github.io/webcomponents/spec/custom/#custom-element-conformance
Instead you need to move the reading of the children into your connected callback:
class jookahGallery extends HTMLElement {
constructor() {
super();
this._childrenRead = false;
const shadowRoot = this.attachShadow({mode: 'open'});
const template = document.createElement('template');
template.innerHtml = `Place your template here`;
const instance = template.content.cloneNode(true);
shadowRoot.appendChild(instance);
}
connectedCallback() {
if (!this._childrenRead) {
this._childrenRead = true;
if (this.hasChildNodes()) {
console.log('there are nodes')
}else{
console.log('NO nodes')
}
}
}
}
customElements.define('jookah-gallery', jookahGallery);
You can also use <slot> to embed your children. But there are some CSS issues you need to be aware of when using slots.
Remember that shadowDOM is not supported in all browsers and is not a simple polyfill. So if you are only working on Chrome and Safari, go for it. If you are planning to support a broader range of browsers then you might not want to use ShadowDOM just yet.
https://alligator.io/web-components/composing-slots-named-slots/
Also read more here: How to use child elements in Web Components

Categories