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

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);

Related

connectedCallback () on custom elements cannot use forEach to loop data on javascript

can anyone provide a solution to the problem that I'm currently encountering? I created a custom element where this custom element must have been detected on the dom, but I need to have the data contained in this custom element loaded, so my program code is like this.
import './menu-item.js';
class MenuList extends HTMLElement {
// forEach cannot be used if I use the ConnectedCallback () method
connectedCallback() {
this.render()
}
// my data can be from this method setter
set menus(menus) {
this._menus = menus;
this.render();
}
render() {
this._menus.forEach(menu => {
const menuItemElement = document.createElement('menu-item');
menuItemElement.menu = menu;
this.appendChild(menuItemElement);
});
}
}
customElements.define('menu-list', MenuList);
and this is the data I sent in the main.js file
import '../component/menu/menu-list.js';
import polo from '../data/polo/polo.js';
const menuListElement = document.querySelector('menu-list');
menuListElement.menus = polo;
please give me the solution.
The connectedCallback runs before the menus=polo statement.
So there is no this._menus declared.
If all the menus setter does is call render, then why not merge them:
set menus(menus) {
this.append(...menus.map(menu => {
const menuItemElement = document.createElement('menu-item');
menuItemElement.menu = menu;
return menuItemElement;
}));
}

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();
}
}

Javascript ES6 Classes - Method cant access class property defined inside class constructor

So i was trying to structure my code inside a class so it can be more organized, but iam struggling. I have the code:
class App {
constructor() {
// Get elements from DOM
const titleBox = document.getElementById('titleBox');
const navBox = document.getElementById('navBox');
const navLinks = document.querySelectorAll('.header__listLink');
const headerTitle = document.getElementById('headerTitle');
const headerSubtitle = document.getElementById('headerSubtitle');
const ulNav = document.getElementById('ulNav');
const ulNavLinks = document.querySelectorAll('.ulNavLink');
// for each nav link, add an event listener, expanding content area
navLinks.forEach((link) => {
link.addEventListener('click', this.clickedLinkState);
});
}
clickedLinkState(e) {
e.preventDefault();
titleBox.classList.remove("header__title-box");
titleBox.classList.add("header__title-box--linkClicked");
headerTitle.classList.remove("header__title");
headerTitle.classList.add("header__title--linkClicked");
headerSubtitle.classList.remove("header__subtitle");
headerSubtitle.classList.add("header__subtitle--linkClicked");
ulNav.classList.remove("header__listInline");
ulNav.classList.add("header__listInline--linkClicked");
navBox.classList.remove("header__nav-box");
navBox.classList.add("header__nav-box--linkClicked");
ulNavLinks.forEach((navLink) => {
navLink.classList.remove("header__listLink");
navLink.classList.add("header__listLink--linkClicked");
});
}
}
const app = new App();
And i got the error: "main.js:40 Uncaught ReferenceError: ulNavLinks is not defined
at HTMLLIElement.clickedLinkState (main.js:40)". the 'ulNavLinks' is a nodeList.
I was trying to define the elements using 'this.titleBox = ...', for exemple, but it got even worse, i could not access it from my clickedLinkState method. Outside the class it was working.
Why i cant access the 'ulNavLinks' inside my method? and why i cant access my propesties inside the method if i declare them 'this.titleBox', 'this.navBox'?
In JavaScript, as for now, instance properties can only being defined inside class methods using keyword this (here is the doc).
Also there is an experimental feature of supporting public/private fields, which you may use with some build steps due to poor browser support.
Make sure to use this:
class App {
constructor() {
// Get elements from DOM
this.titleBox = document.getElementById('titleBox');
this.navBox = document.getElementById('navBox');
this.navLinks = document.querySelectorAll('.header__listLink');
this.headerTitle = document.getElementById('headerTitle');
this.headerSubtitle = document.getElementById('headerSubtitle');
this.ulNav = document.getElementById('ulNav');
this.ulNavLinks = document.querySelectorAll('.ulNavLink');
// for each nav link, add an event listener, expanding content area
this.navLinks.forEach((link) => {
link.addEventListener('click', this.clickedLinkState.bind(this));
});
}
clickedLinkState(e) {
e.preventDefault();
this.titleBox.classList.remove("header__title-box");
this.titleBox.classList.add("header__title-box--linkClicked");
this.headerTitle.classList.remove("header__title");
this.headerTitle.classList.add("header__title--linkClicked");
this.headerSubtitle.classList.remove("header__subtitle");
this.headerSubtitle.classList.add("header__subtitle--linkClicked");
this.ulNav.classList.remove("header__listInline");
this.ulNav.classList.add("header__listInline--linkClicked");
this.navBox.classList.remove("header__nav-box");
this.navBox.classList.add("header__nav-box--linkClicked");
this.ulNavLinks.forEach((navLink) => {
navLink.classList.remove("header__listLink");
navLink.classList.add("header__listLink--linkClicked");
});
}
}
const app = new App();

Iterate over HTMLCollection in custom element

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!

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