in pure js create 2 nested components and the second one need to update dom element in javascript

To create nested components in pure JS, we can follow the below approach:

  1. First, we create a parent component and its corresponding DOM element.
index.tsx
class ParentComponent {
  constructor(parentElement) {
    this.parentElement = parentElement;
  }
  
  render() {
    const childDivElement = document.createElement("div");
    const childComponent = new ChildComponent(childDivElement);
    
    this.parentElement.appendChild(childDivElement);
    childComponent.render();
  }
}
331 chars
14 lines
  1. Then, within the parent component, we create a child component and assign a corresponding DOM element to it.
index.tsx
class ChildComponent {
  constructor(childDivElement) {
    this.childDivElement = childDivElement;
  }
  
  render() => {
    this.childDivElement.innerHTML = "Hello World!";
  }
}
182 chars
10 lines
  1. Finally, we can update the DOM element of the child component by creating and invoking a update() function within the child component.
index.tsx
class ChildComponent {
  constructor(childDivElement) {
    this.childDivElement = childDivElement;
  }
  
  render() {
    this.childDivElement.innerHTML = "Hello World!";
  }
  
  update(newText) {
    this.childDivElement.innerHTML = newText;
  }
}
252 chars
14 lines

Now, we can instantiate the parent component and render it to the desired parent DOM element as shown below:

index.tsx
const parentElement = document.getElementById("parent");
const parentComponent = new ParentComponent(parentElement);

parentComponent.render();
144 chars
5 lines

To update the DOM element of the child component, we can simply invoke the update() function of the child component as shown below:

index.tsx
const childComponent = new ChildComponent(document.createElement("div"));
childComponent.render();

childComponent.update("New Text!");
136 chars
5 lines

This will update the child DOM element from "Hello World!" to "New Text!".

gistlibby LogSnag