How to Manipulate the DOM with JavaScript (Complete)

The DOM (Document Object Model) is a representation of an HTML page's structure as a tree of objects that can be accessed and manipulated using JavaScript. By manipulating the DOM,...

How to Manipulate the DOM with JavaScript (Complete)
Advertisement

The DOM (Document Object Model) is a representation of an HTML page's structure as a tree of objects that can be accessed and manipulated using JavaScript. By manipulating the DOM, we can change page content, add or remove elements, change styles, and respond to user interaction — all without needing to reload the page. This is the essence of an interactive and dynamic web.

Selecting DOM Elements

The first step is selecting the element you want to manipulate. There are several ways to do this:

// getElementById — select by ID (the fastest)
const judulUtama = document.getElementById('judul');

// querySelector — select the first matching element (like a CSS selector)
const tombolKirim = document.querySelector('#form button[type="submit"]');
const paragrafPertama = document.querySelector('p');

// querySelectorAll — select ALL matching elements (returns a NodeList)
const semuaItem = document.querySelectorAll('.item-list li');
const semuaGambar = document.querySelectorAll('img');

// getElementsByClassName — select by class
const kartu = document.getElementsByClassName('card');

console.log(judulUtama); // the <h1 id="judul"> element
console.log(semuaItem.length); // the number of items found

Changing an Element's Content

Once we've selected an element, we can change its content:

Advertisement
const judul = document.getElementById('judul');

// innerHTML — can insert HTML inside it
judul.innerHTML = '<span class="highlight">Hello World!</span>';

// textContent — plain text only, safer against XSS attacks
judul.textContent = 'Hello World!';

// Changing an input's value
const inputNama = document.getElementById('nama');
inputNama.value = 'Budi Santoso';

// Changing attributes
const gambar = document.querySelector('img');
gambar.src = '/images/foto-baru.jpg';
gambar.alt = 'A cool new photo';

Changing an Element's Style

There are two ways to change an element's appearance: directly through the style property, or by adding/removing CSS classes:

const kotak = document.getElementById('kotak');

// Method 1: Change the style directly (camelCase, not kebab-case)
kotak.style.backgroundColor = '#3498db';
kotak.style.color = 'white';
kotak.style.padding = '20px';
kotak.style.borderRadius = '8px';

// Method 2 (more recommended): Manipulate CSS classes
kotak.classList.add('aktif');       // Add a class
kotak.classList.remove('tersembunyi'); // Remove a class
kotak.classList.toggle('fokus');    // Toggle (add if not present, remove if present)

// Check whether an element has a certain class
if (kotak.classList.contains('aktif')) {
  console.log('The box is currently active!');
}

Creating and Adding New Elements

We can create new elements and insert them into the page:

// Create a new element
const itemBaru = document.createElement('li');
itemBaru.textContent = 'Item 4';
itemBaru.classList.add('item-list');

// Add it inside another element
const daftarUl = document.getElementById('daftar');
daftarUl.appendChild(itemBaru); // Add at the end

// insertBefore — add before a specific element
const itemPertama = daftarUl.firstElementChild;
const itemSisipan = document.createElement('li');
itemSisipan.textContent = 'Topmost item (inserted)';
daftarUl.insertBefore(itemSisipan, itemPertama);

// insertAdjacentHTML — a quick way to insert HTML
daftarUl.insertAdjacentHTML('beforeend', '<li class="item-list">Last item</li>');

Removing Elements

// Remove an element from the DOM
const itemHapus = document.getElementById('item-hapus');
itemHapus.remove(); // Modern and direct

// The old way (still valid)
const parent = document.getElementById('daftar');
const child = parent.querySelector('.item-dihapus');
parent.removeChild(child);

A Real Example: A Simple To-Do List

Let's combine everything we've learned in a practical example:

// The required HTML:
// <input id="input-todo" type="text" placeholder="Add a task...">
// <button id="btn-tambah">Add</button>
// <ul id="daftar-todo"></ul>

const inputTodo = document.getElementById('input-todo');
const btnTambah = document.getElementById('btn-tambah');
const daftarTodo = document.getElementById('daftar-todo');

function tambahTugas() {
  const teks = inputTodo.value.trim();
  if (!teks) return; // Don't add if empty

  const li = document.createElement('li');
  li.innerHTML = `
    <span>${teks}</span>
    <button class="btn-hapus">Delete</button>
  `;

  // Add a working delete button
  li.querySelector('.btn-hapus').addEventListener('click', () => {
    li.remove();
  });

  daftarTodo.appendChild(li);
  inputTodo.value = ''; // Clear the input
  inputTodo.focus();    // Return focus to the input
}

btnTambah.addEventListener('click', tambahTugas);

// Press Enter to add
inputTodo.addEventListener('keypress', (e) => {
  if (e.key === 'Enter') tambahTugas();
});

DOM Traversal

We can also move between elements using traversal properties:

  • parentElement — access the parent element
  • children — access all direct children
  • firstElementChild and lastElementChild — the first/last child
  • nextElementSibling and previousElementSibling — the sibling before/after

Conclusion

DOM manipulation is a core skill that every web developer must master. By understanding how to select elements, change content and styles, and add or remove elements dynamically, you can already build interactive web pages without any framework. The best practice is to build small projects like a to-do list, a calculator, or a simple quiz using pure JavaScript.

Advertisement
manipulasi dom javascript cara mengubah dom javascript dom tutorial getelementbyid queryselector dom html javascript
Share this article
Back to Blog
🚀 Partner Recommendation

Need Premium Source Code & Business Apps?

Access Laravel applications, POS systems, School Management, Clinic Software, ERP solutions, and ready-to-use premium source code at GudangCode.

GudangCode
  • ✔ Premium Source Code
  • ✔ Ready-to-Use Systems
  • ✔ Lifetime Updates
  • ✔ Lifetime Membership
  • ✔ Daily App Updates
Join Membership →
Advertisement
Advertisement