Dears,
I have a task to create custom HTML component, display it 100 times, add button to it, which would remove it and also every 3rd component should be clickable and change color on click. So far I have this https://codepen.io/GosiaPtak/pen/abOZmyq
class ElementList extends HTMLElement {
constructor() {
super();
let counter = 100;
const div = '';
const btn = '';
}
connectedCallback() {
this.div = document.createElement('div');
this.div.innerHTML = 'i am div';
this.btn = document.createElement('button');
this.btn.innerHTML = 'Click me';
this.div.appendChild(this.btn);
this.appendChild(this.div);
}
}
customElements.define('element-list', ElementList);
but I am not able to place the while loop properly, so it would display it 100 times.
could you please help me, I am learning it from here: https://javascript.info/custom-elements
Kind regards,
You are defining a custom element with your code which represents one instance of the object. To now create multiple of these just use basic javascript outside of the class definition like the code below shows.
class ElementList extends HTMLElement {
constructor() {
super();
const div = '';
const btn = '';
}
connectedCallback() {
this.div = document.createElement('div');
this.div.innerHTML = 'i am div';
this.btn = document.createElement('button');
this.btn.innerHTML = 'Click me';
this.div.appendChild(this.btn);
this.appendChild(this.div);
}
}
customElements.define('element-list', ElementList);
for(let i = 0; i <= 100; i++) {
let item = document.createElement('element-list');
document.body.appendChild(item);
}
With this for loop and maybe a parameter which you could pass to your object you can realize things like every third should be clickable.