Monday, May 12, 2025

BIS601 Full Stack Development - React -Difference between createElement and appendChild

What is the difference between createElement(tag)

and appendChild(node) and how does this relate

to React?

createElement(tag) vs appendChild(node)


Method

Purpose

document.createElement(tag)

Creates a new DOM element (not in the page yet)

parent.appendChild(child)

Adds a node as the last child of another node


Using Both to Create the DOM Tree:

We’ll build:

<form>

  <label></label>

  <ul>

    <li></li>

    <li></li>

  </ul>

</form>


JavaScript Code:

const form = document.createElement('form');

const label = document.createElement('label');

const ul = document.createElement('ul');

const li1 = document.createElement('li');

const li2 = document.createElement('li');


// Build the structure

ul.appendChild(li1);

ul.appendChild(li2);


form.appendChild(label);

form.appendChild(ul);


// Attach to the page (e.g., body)

document.body.appendChild(form);


How Does This Relate to React?

In React, React.createElement() is a virtual version of this DOM API.

For example:

React.createElement('form', null, 

  React.createElement('label', null),

  React.createElement('ul', null,

    React.createElement('li', null),

    React.createElement('li', null)

  )

)


React uses this behind the scenes to build a Virtual DOM, which is then efficiently synced with the real DOM.

No comments:

Post a Comment