Skip to content
Advertisement

Is there a way to create an HTMLElement, which will delete itself later?

I have an abstract class “Component”

abstract class Component {
    protected container: HTMLElement;
  
    constructor(tagName: string, className: string) {
      this.container = document.createElement(tagName);
      this.container.className = className;
    }
  
    render() {
      return this.container;
    }
}

Other classes extend this class. Is there a way to make render() return a this.container, which later will be deleted from DOM, i.e. after 5 seconds?

Advertisement

Answer

Have you tried using setTimeout?

abstract class Component {
    protected container: HTMLElement;
  
    constructor(tagName: string, className: string) {
      this.container = document.createElement(tagName);
      this.container.className = className;
    }
  
    render() {
      setTimeout(() => {
        this.container.remove()
      }, 5000)
      return this.container;
    }
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement