Advance JavaScript (DOM, BOM, Web API) / Document Object Model

Manipulating Elements - Part 1

βœ… createElement() - Create a new element

πŸ”Ή What is document.createElement()?

document.createElement() is used to create a new HTML element using JavaScript and then attach it to the DOM.

let element = document.createElement('tagName');
  • It returns a new HTML element (Node).

  • The element is created in memory and not visible until added to the DOM.

1️⃣ Create and Add a <div>

<!DOCTYPE html>
<html>
<body>
  <script>
    const div = document.createElement('div');
    div.innerHTML = '<p>CreateElement example</p>';
    document.body.appendChild(div);
  </script>
</body>
</html>
<p>CreateElement example</p>

2️⃣ Add id and class to an Element

const div = document.createElement('div');
div.id = 'content';
div.className = 'note';
div.innerHTML = '<p>CreateElement example</p>';

document.body.appendChild(div);
<div id="content" class="note">
  <p>CreateElement example</p>
</div>

3️⃣ Add Text to a <div>

const div = document.createElement('div');
const text = document.createTextNode('CreateElement example');

div.appendChild(text);
document.body.appendChild(div);
CreateElement example

4️⃣ Add an Element Inside Another Element

const div = document.createElement('div');
const h2 = document.createElement('h2');

h2.textContent = 'Heading inside div';
div.appendChild(h2);

document.body.appendChild(div);
<h2>Heading inside div</h2>

5️⃣ Create List Items (<li>)

✏️ HTML

<ul id="menu">
  <li>Home</li>
</ul>

🧠 JavaScript

const menu = document.querySelector('#menu');

let li = document.createElement('li');
li.textContent = 'Products';
menu.appendChild(li);

li = document.createElement('li');
li.textContent = 'About Us';
menu.appendChild(li);
<ul id="menu">
  <li>Home</li>
  <li>Products</li>
  <li>About Us</li>
</ul>

6️⃣ Create a <script> Dynamically

const script = document.createElement('script');
script.src = '/lib.js';
document.body.appendChild(script);

πŸ”„ Async Script

function loadJSAsync(url) {
  const script = document.createElement('script');
  script.src = url;
  script.async = true;
  document.body.appendChild(script);
}

loadJSAsync('/lib.js');

πŸ‘€ Summary

  • document.createElement() β†’ creates an element

  • appendChild() β†’ adds it to the DOM

  • Use:

    • innerHTML β†’ add HTML

    • textContent / createTextNode() β†’ add text

    • id, className β†’ set attributes

Element is created first β†’ added later β†’ then visible on page


βœ… appendChild() - append a node to a list of child nodes of a specified parent node.

πŸ”Ή What is appendChild()?

appendChild() is used to add a node as the last child of a parent element.

parentNode.appendChild(childNode);

πŸ‘‰ Key Points

  • It adds elements at the end of a parent.

  • It returns the appended child.

  • If the child already exists in the DOM, it is moved, not duplicated.

1️⃣ Basic appendChild() Example

✏️ HTML

<ul id="menu"></ul>

🧠 JavaScript

function createMenuItem(name) {
  const li = document.createElement('li');
  li.textContent = name;
  return li;
}

const menu = document.querySelector('#menu');

menu.appendChild(createMenuItem('Home'));
menu.appendChild(createMenuItem('Services'));
menu.appendChild(createMenuItem('About Us'));
<ul id="menu">
  <li>Home</li>
  <li>Services</li>
  <li>About Us</li>
</ul>

πŸ‘‰ How it Works

  • Create <li> using createElement()

  • Add text using textContent

  • Attach <li> to <ul> using appendChild()

2️⃣ Moving an Existing Node (Important Concept)

✏️ HTML (Before)

<ul id="first-list">
  <li>Everest</li>
  <li>Fuji</li>
  <li>Kilimanjaro</li>
</ul>

<ul id="second-list">
  <li>Karakoram Range</li>
  <li>Denali</li>
  <li>Mont Blanc</li>
</ul>

🧠 JavaScript

const firstList = document.querySelector('#first-list');
const everest = firstList.firstElementChild;

const secondList = document.querySelector('#second-list');
secondList.appendChild(everest);
<ul id="first-list">
  <li>Fuji</li>
  <li>Kilimanjaro</li>
</ul>

<ul id="second-list">
  <li>Karakoram Range</li>
  <li>Denali</li>
  <li>Mont Blanc</li>
  <li>Everest</li>
</ul>

❗️Important Note

  • appendChild() moves the element

  • The element is removed from its old parent

  • No duplicate nodes are created

🧾 Summary

  • appendChild() β†’ adds a child at the end

  • Works with new or existing elements

  • Existing elements are moved, not copied

  • Commonly used with:

    • createElement()

    • querySelector()

    • textContent

Create β†’ Append β†’ Display


βœ… textContent() and innerHTML()

πŸ”Ή What is textContent?

textContent is used to get or set only the text of an element and all its child nodes.

let text = node.textContent;

1️⃣ Reading textContent

✏️ HTML

<div id="note">
  JavaScript textContent Demo!
  <span style="display:none">Hidden Text!</span>
  <!-- comment -->
</div>

🧠 JavaScript

const note = document.getElementById('note');
console.log(note.textContent);
JavaScript textContent Demo!
Hidden Text!

πŸ‘‰ Key Point

  • Includes hidden text

  • Ignores HTML comments

  • Does not care about CSS

2️⃣ textContent vs innerText

console.log(note.innerText);
JavaScript textContent Demo!

πŸ” Difference

Property

Hidden Text

CSS Aware

Performance

textContent

βœ… Yes

❌ No

⚑ Fast

innerText

❌ No

βœ… Yes

🐒 Slower (reflow)

βœ” innerText triggers reflow (browser recalculates layout)

3️⃣ Setting textContent

note.textContent = 'This is a note';
This is a note

πŸ‘‰ Important

  • Removes all child elements

  • Inserts only plain text

  • Safe from XSS attacks


πŸ”Ή What is innerHTML?

innerHTML is used to get or set HTML markup inside an element.

element.innerHTML;
element.innerHTML = newHTML;

4️⃣ Reading innerHTML

✏️ HTML

<ul id="menu">
  <li>Home</li>
  <li>Services</li>
</ul>

βœ… JavaScript

const menu = document.getElementById('menu');
console.log(menu.innerHTML);
<li>Home</li>
<li>Services</li>

5️⃣ innerHTML Reflects Live DOM Changes

🧠 JavaScript

const li = document.createElement('li');
li.textContent = 'About Us';
menu.appendChild(li);

console.log(menu.innerHTML);
<li>Home</li>
<li>Services</li>
<li>About Us</li>

βœ” Shows original + dynamically added content

6️⃣ Setting innerHTML

document.body.innerHTML = '';
Page cleared

❗️ Warning

  • Replaces entire content

  • Removes all event listeners

πŸ” Security Risk with innerHTML

❌ Dangerous Example

main.innerHTML = `<img src="1" onerror="alert('Hacked!')">`;

πŸ“€ Output

🚨 Alert pops up β†’ XSS vulnerability

βœ… Safe Alternative

main.textContent = `<img src="1" onerror="alert('Hacked!')">`;
<img src="1" onerror="alert('Hacked!')">

βœ” Treated as plain text

🧾 Final Comparison

Feature

textContent

innerHTML

Gets text

βœ… Yes

❌ No

Gets HTML

❌ No

βœ… Yes

Parses HTML

❌ No

βœ… Yes

Safe from XSS

βœ… Yes

❌ No

Removes children when set

βœ… Yes

βœ… Yes


πŸ“ Summary

  • Use textContent for:

    • Plain text

    • Better performance

    • Security-safe content

  • Use innerHTML for:

    • Inserting HTML

    • Dynamic UI updates

    • Only with trusted content

βœ… Rule of Thumb:

If it’s text β†’ textContent

If it’s HTML β†’ innerHTML