JavaScript: DOM Manipulation

🗓 Last updated: 2026-11-30👤 Written by: Casey✓ Reviewed by: Dana🏷 Category: JavaScript Tutorial

DOM (Document Object Model) is a tree that the browser creates from the HTML document. By operating on this tree with JavaScript, you can dynamically change the page's content, structure, and attributes—like picking fruit from a tree, grafting new branches, or cutting dead wood.


Related DOM Methods:document.createElement querySelectorAll removeAttribute querySelector setAttribute getAttribute textContent appendChild innerHTML NodeList remove() class href

1. Selecting Elements

The first step in DOM manipulation is always "find it first".

Method Returns Description
getElementById('id') Single element Fastest, id is unique
getElementsByClassName('cls') HTMLCollection Live collection, syncs with DOM changes
getElementsByTagName('tag') HTMLCollection Same as above
querySelector('selector') Single element CSS selector, returns first match
querySelectorAll('selector') NodeList Static collection, doesn't change with DOM
💡 Tip: querySelector family vs getElementBy*: the former uses CSS selectors (more flexible), the latter has slightly better performance. For daily development, prefer querySelector—it's more intuitive.

▶ Example: Comparing Five Selection Methods

▶ Try it Yourself

2. Modifying Content

After finding an element, the most common need is to change "what it says".

⚠️ Note: Never use innerHTML to insert user-supplied content, otherwise attackers can inject malicious scripts. It's like posting a letter from a stranger directly to the bulletin board—the letter might contain a "bomb".

▶ Example: textContent vs innerHTML

▶ Try it Yourself

3. Modifying Attributes

HTML element attributes (id, class, src, href, etc.) can also be read and written with JS.

Method Description
getAttribute('name') Read attribute value
setAttribute('name', 'value') Set attribute
removeAttribute('name') Remove attribute
💡 Tip: Some attributes can be accessed directly with dot notation: el.id, el.className, el.src. But for custom attributes (data-*), use getAttribute or el.dataset.

▶ Try it Yourself

4. Creating and Inserting Elements

One of the core DOM manipulation abilities: "create" an element out of thin air, then attach it to the tree.

Method Description
createElement('tag') Create element node
createTextNode('text') Create text node
appendChild(child) Append to end
insertBefore(new, ref) Insert before ref

▶ Example: Dynamically Adding List Items

▶ Try it Yourself

5. Removing and Cloning Elements

Method Description
removeChild(child) Parent removes child node
remove() Element removes itself (newer API)
cloneNode(true/false) true = deep clone (including children), false = shallow clone
💡 Tip: remove() is simpler than removeChild(), but if you need to get the removed node for further processing, use removeChild()—it returns the removed node.

▶ Example: Removing and Cloning

▶ Try it Yourself

Related DOM Methods:document.createElement querySelectorAll removeAttribute querySelector setAttribute getAttribute textContent appendChild innerHTML NodeList remove() class href

❓ FAQ

Q What is the difference between querySelector and querySelectorAll in JavaScript?
A querySelector returns the first matching element, or null if nothing matches; querySelectorAll returns a static NodeList of all matching elements, or an empty collection if nothing matches. The former is suited to working with a single element, while the latter is suited to iterating over many. Note that the result of querySelectorAll does not update automatically as the DOM changes.
Q Why do I get a TypeError when I grab an element with querySelector and immediately change its properties?
A Usually the selector didn't match any element, so it returned null, and reading or setting properties on null throws a TypeError. Check before operating: const el = document.querySelector('.xxx'); if (el) { el.textContent = 'hi'; }. You can also check the selector spelling and whether the element already exists when the script runs.
Q To dynamically add a new element to the page, should I use createElement or innerHTML?
A When you need fine-grained control over nodes, bind events, or insert existing nodes, using document.createElement with appendChild/insertBefore is safer. When you're just writing simple HTML strings in bulk, innerHTML is more concise, but it rebuilds inner nodes and may introduce XSS risks. Using appendChild with an existing node moves it rather than copying it, so to keep the original node you should first cloneNode(true).

📖 Summary

📝 Exercises

  1. Basic: Create a page that uses createElement and appendChild to dynamically generate a list containing 5 city names.
  2. Intermediate: Add a delete button to the list from the previous exercise. When clicked, use removeChild to delete the corresponding list item.
  3. Challenge: Implement a simple "note manager"—an input field + add button. Each time you add a note, create a card with a delete button. Clicking the delete button removes that card.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏