Register to get access to free programming courses with interactive exercises

Manipulating the Dom tree JS: DOM API

A DOM tree can change when the browser has already been rendered it. This fact provides a key opportunity for creating interactive applications. In this lesson, we will discuss how to manipulate DOM trees and what features we can get by doing so.

innerHTML

The easiest way to update a part of a DOM tree is the innerHTML property:

<ul>
  <li>item 1</li>
  <li>item 2</li>
</ul>
const body = document.body;
console.log(body);
// <ul><li>item 1</li><li>item 2</li></ul>

body.innerHTML = '<b>make</b> love';
console.log(body.innerHTML);
// <b>make</b> love

console.log(body.childNodes);
// [b, text]

The value of this property completely replaces the descendants of the element on which we have called it. All the HTML found inside is analyzed and becomes part of the tree.

Imagine we try to insert plain text with a potential HTML in it. It raises the possibility of XSS attacks, so we should use a different property – textContent.

The property textContent works almost identically, it replaces all descendants, too. The main difference between these properties is that textContent treats its content as plain text anyway, even if there's HTML:

document.body.textContent = '<b>make</b> love';
console.log(document.body.innerHTML);
// All special characters are replaced
// "&lt;b&gt;make&lt;/b&gt; love"

The property innerHTML works with strings, which is only convenient if we're working with a static DOM representation. There are special functions suitable for generating a DOM tree dynamically.

Creating nodes

// Creating a text node
const textNode = document.createTextNode('life is life');

// Creating a p element
const pEl = document.createElement('p');

// Adding the textNode to the end of the childNodes list of the element pEl
pEl.append(textNode);
// pEl.textContent = 'life is life';

const el = document.createElement('div');
el.append(pEl);

console.log(el);
// <div><p>life is life</p></div>

When the code creates a DOM dynamically, it looks like a nesting doll. Once created, some elements are put into others all the time. The code that creates trees will look like this in any language.

Insert

ParentNode.prepend() adds the nodes passed by the first child to ParentNode:

const div = document.createElement('div');
div.innerHTML = '<span>Hexlet</span>';

const el = document.createElement('p');
el.textContent = 'prepend';
div.prepend(el);
// <div>
//   <p>prepend</p>
//   <span>Hexlet</span>
// </div>

ParentNode.append() adds the nodes passed by the last child to ParentNode:

const div = document.createElement('div');
div.innerHTML = '<span>Hexlet</span>';

const el = document.createElement('p');
el.textContent = 'append';
div.append(el);
// <div>
//   <span>Hexlet</span>
//   <p>append</p>
// </div>

childNode.before(...nodes) inserts nodes into the list of children of the parent node of this childNode right before the childNode itself:

const div = document.createElement('div');
div.innerHTML = '<span>Hexlet</span>';
// Must be inserted into the DOM tree
document.body.append(div);

const el = document.createElement('p');
el.textContent = 'content';
div.before(el);
// <p>content</p>
// <div>
//   <span>Hexlet</span>
// </div>

childNode.after(...nodes) – inserts nodes into the list of children of the parent node of this childNode immediately after it:

const div = document.createElement('div');
div.innerHTML = '<span>Hexlet</span>';
// Must be inserted into the DOM tree
document.body.append(div);

const el = document.createElement('p');
el.textContent = 'content';
div.after(el);
// <div>
//   <span>Hexlet</span>
// </div>
// <p>content</p>

node.replaceWith(...nodes) replaces a single node with multiple ones. The node itself disappears from the DOM tree, but it remains available in the code:

const div = document.createElement('div');
div.innerHTML = '<span>Hexlet</span>';
// Must be inserted into the DOM tree
document.body.append(div);

const el = document.createElement('p');
el.textContent = 'content';
div.replaceWith(el);
// In the DOM tree, p replaces div
// <p>content</p>

node.remove() removes the current node.

Old API

The functions described above only appeared lately. Before that, programmers wrote most of the code using the other functions listed below:

  • parent.appendChild(el) – adds el to the end of the list of children
  • parent.insertBefore(el, nextElSibling) – adds el to the list of children of a parent before the nextElSibling
  • parent.removeChild(el) – removes el from the children of a parent
  • parent.replaceChild(newEl, el) – replaces el with newEl

Cloning

Sometimes, you need to create an element similar to an existing one. Of course, you can do this 100% manually by copying the properties of one into the properties of another. But there's an easier way:

const newEl = el.cloneNode(true);

The value true shows that we make a deep copy, meaning a copy of that element with all its descendants.


Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

Bookmate
Health Samurai
Dualboot
ABBYY
Suggested learning programs
profession
Development of front-end components for web applications
10 months
from scratch
Start at any time

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.