How to create to-do list using CustomElements

Creating a to-do list using custom elements can involve several steps:

  1. Define the custom element that represents a single to-do item. This custom element should extend the HTMLElement class and define any properties or methods that you want it to have, such as a title, a description, and a checkbox to indicate whether the item is completed or not.
class TodoItem extends HTMLElement {
constructor() {
super();
this.innerHTML = `
<input type="checkbox">
<label>Title</label>
<button>Delete</button>
`;
}
get title() {
return this.querySelector('label').textContent;
}
set title(value) {
this.querySelector('label').textContent = value;
}
get completed() {
return this.querySelector('input').checked;
}
set completed(value) {
this.querySelector('input').checked = value;
}
}
customElements.define('todo-item', TodoItem);

2. Create another custom element, that will represent the whole to-do list. This element should be responsible for rendering the to-do items and handling events such as adding new items, deleting items, and marking items as completed.

class TodoList extends HTMLElement {
constructor() {
super();
this.innerHTML = `
<form>
<input type="text" placeholder="Add new item">
<button>Add</button>
</form>
<ul></ul>
`;
this.querySelector('form').addEventListener('submit', this.addItem.bind(this));
}
addItem(event) {
event.preventDefault();
const input = this.querySelector('input');
if (!input.value) return;
const item = document.createElement('todo-item');
item.title = input.value;
input.value = '';
this.querySelector('ul').appendChild(item);
}
}
customElements.define('todo-list', TodoList);

3. Finally, you can use the <todo-list> element in your HTML page to display the to-do list.

<todo-list></todo-list>

The above example is a basic example of creating a to-do list using custom elements. You can add more functionality like adding styles, adding the delete functionality, saving the todo-list state in the browser and many more. The main idea is that you are using the custom elements to create reusable and modular components that can be easily added to your web pages.