Register to get access to free programming courses with interactive exercises

Manipulating the Dom tree JS: DOM API

The fact that DOM trees can change when they've already been rendered in the browse provides a key opportunity for creating interactive applications.

innerHTML

The easiest way to update part of a DOM 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 that it was called on. All the HTML found inside is analyzed and becomes part of the tree. If you try to insert plain text that could potentially contain HTML (this can allow XSS attacks to happen), then it's better to use a different property – textContent.

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

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"

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');

// Add 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>

Code that creates a DOM dynamically looks like a nesting doll. Once created, some elements are put into others all the time. This is what code that creates trees will look like in any language.

Insert

ParentNode.prepend() adds the node (or 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 node (or 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. 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 recently. Most of the code was written 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 that's similar to an existing one. You can, of course, 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);

true means that you need to make a deep copy, i.e., a copy not just of that element, but all its descendants.


Hexlet Experts

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

The Hexlet support team or other students will answer you.

About Hexlet learning process

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:

<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.bookmate">Bookmate</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.healthsamurai">Healthsamurai</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.dualboot">Dualboot</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.abbyy">Abbyy</span>
Suggested learning programs

From a novice to a developer. Get a job or your money back!

Frontend Developer icon
Profession
beginner
Development of front-end components for web applications
start anytime 10 months

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.