Exercise 12: Create Element with Attributes and Children

Problem Statement

Function `createElement(tag, attrs, children)` banao jo element create kare with attributes aur children. Example: createElement("div", {class: "container"}, ["Hello"])

Sample Output:

createElement("div", {class: "container"}, ["Hello"]) => <div class="container">Hello</div>

Solution

const createElement = (tag, attrs = {}, children = []) => {
  const el = document.createElement(tag);
  Object.entries(attrs).forEach(([key, value]) => el.setAttribute(key, value));
  children.forEach(child => el.appendChild(typeof child === "string" ? document.createTextNode(child) : child));
  return el;
};

Explanation

Overall Goal:

  • Element create karna with attributes aur children.

Real world:

  • Dynamic DOM: element creation.
  • Component rendering: element building.