New to front-end coding, have you ever found your website "inert" and wondered how to click a button and something will appear, or how the data the user enters can instantly change the interface? I used to be the same way. The core problem lies in not being able to "tame" the DOM. Mastering DOM JavaScript HTML element manipulation is the key to turning a static HTML page into an immersive experience. If you're looking for the Learn Basic JavaScript for Beginners 2026 route, then a deep understanding of the DOM is a must-stop. In this article, I will share all my real combat experience gathered after many years of working in the profession to help you master it.
Understand the root of the problem: What is the JavaScript DOM?
DOM (Document Object Model) is a W3C standard programming interface that allows JavaScript to access and manipulate elements on the web page. It turns the entire HTML document into a tree structure that code can interact with.
Many beginners often wonder what DOM JavaScript is? and why we hear about it so much. In fact, when Browser loads a web page, it doesn't just read lines of plain HTML text. It will translate that code into an in-memory object model. This is the only bridge for programming languages to "talk" and interact with your website. Without the DOM, JavaScript would be completely blind and wouldn't know what elements your web page has.
The DOM tree is not a tree, but a map of the web page
The DOM tree is a hierarchical structure, in which each HTML tag, attribute, or text becomes a separate DOM Node under the management of the document object.
Hãy tưởng tượng trang web của bạn như một cuốn sách. Đối tượng document chính là toàn bộ cuốn sách đó, là điểm bắt đầu của mọi thứ [1]. Bên trong nó, thẻ <html> là chương lớn nhất (Root node), chứa các phần nhỏ hơn là <head> và <body>. Mỗi Phần tử HTML như thẻ <h1>, <p> hay <div> bên trong đều là một Node DOM [1].
For ease of visualization, the DOM Tree is often divided into 3 main types of Node:
- Element Node: Chính là các thẻ HTML (ví dụ:
<div>,<a>). - Text Node: Là đoạn văn bản nằm bên trong các thẻ HTML.
- Attribute Node: Là các thuộc tính đi kèm với thẻ (ví dụ:
id,class,src).
Understanding this map makes it easy to find your way to any corner of the site to make changes.
Why is "DOM manipulation" a vital skill for Front-end people?
DOM manipulation helps turn a static web page into a dynamic web application, allowing immediate response to user interactions without reloading the entire page.
If you only use HTML and CSS, your website will look like a pre-printed brochure, beautiful but not responsive. The concept of What is DOM Manipulation? It is the ability to use code to change that "flyer" right before the viewer's eyes based on their actions [1]. As a JavaScript Front-end programmer, if you want to create smooth popups, image sliders, or realtime cart updates, you must master this skill. For those who are reviewing basic knowledge, mastering Learning basic HTML and CSS for beginners will create a solid stepping stone before entering this exciting world of Dynamic Web.
The first step can't be wrong: "Grab" gets the HTML element you want
To manipulate any content, you need to use JavaScript DOM element selection methods to "grab" it. You can choose based on ID, Class or tag structure.
Accessing a JavaScript DOM element is like calling out a person's name in a crowd. If you call them by the wrong name, you won't be able to give them the job. Luckily, JavaScript provides us with an extremely diverse and powerful set of DOM element selection methods in JavaScript.
How to select canonical elements: getElementById, getElementsByClassName, getElementsByTagName
These are the three most basic methods to help you quickly search for elements via id, class or HTML tag attributes.
Khi mới vào nghề, getElementById chắc chắn là người bạn thân thiết nhất của bạn vì nó trả về duy nhất một phần tử theo ID một cách cực kỳ chính xác [2].
Nếu bạn muốn lấy một nhóm phần tử, getElementsByClassName và getElementsByTagName sẽ là lựa chọn phù hợp [2]. Tuy nhiên, một lưu ý cực kỳ quan trọng từ kinh nghiệm của mình: hai hàm này trả về một tập hợp gọi là HTMLCollection. Đây là một danh sách "sống" (live collection), nghĩa là nếu cấu trúc DOM thay đổi (bạn thêm hoặc xóa phần tử), danh sách này cũng tự động cập nhật theo ngay lập tức mà không cần bạn phải gọi lại hàm [2].
More "pro", more flexible way to choose: querySelector and querySelectorAll
querySelector and querySelectorAll allow you to select elements using CSS selector syntax, providing maximum flexibility when querying complex nested HTML structures.
Instead of having to remember many different commands, you can simply use querySelector to get the first element that matches the condition, or querySelectorAll to get the entire list of matching elements [2]. Their selling point is that you can pass in any CSS string.
Ví dụ, để chọn thẻ <li> đang có class active nằm trong một <ul> có id là menu, bạn chỉ cần viết: document.querySelector('#menu li.active'). Khác với các phương thức kinh điển, querySelectorAll trả về một NodeList tĩnh (static), nghĩa là nó chỉ chụp lại ảnh của DOM tại thời điểm gọi hàm, không tự động cập nhật nếu DOM thay đổi sau đó [2].
My experience: When should you use querySelector instead of get.. methods?
Use getElementById when you need maximum performance for simple IDs, and use querySelector when you need flexibility to select elements with complex structures.
Dựa trên các cập nhật mới nhất tính đến đầu năm 2026, các bài kiểm tra hiệu năng (benchmark) thực tế vẫn cho thấy getElementById có tốc độ xử lý nhanh hơn querySelector từ 2 đến 10 lần [3]. Lý do là vì nó truy cập trực tiếp vào bảng băm (hash table) lưu trữ ID nội bộ của trình duyệt [3].
Tại Phạm Hải, mình luôn khuyên các bạn trong team: nếu chỉ cần lấy ID đơn giản trong các vòng lặp lớn, hãy ưu tiên dùng getElementById để tối ưu tốc độ [3]. Nhưng nếu phải truy vấn cấu trúc phức tạp, querySelector là lựa chọn hoàn hảo giúp code ngắn gọn và dễ bảo trì hơn [3]. Ngoài ra, để tối ưu hiệu suất tải trang tổng thể, bạn cũng nên tìm hiểu thêm về cách cấu hình defer và async javascript wordpress để các file script chứa lệnh chọn DOM này không chặn quá trình render giao diện ban đầu của người dùng.
Unpredictable changes: Change and update HTML elements
Once elements have been selected, the next step in manipulating the DOM in JavaScript is to change their content, properties, or appearance in response to the user.
Here is when the magic begins. You have full authority to Update DOM element properties and decide what text and color that element will display, or what hidden data it will carry to serve the calculation logic behind it.
Changing content: When to use innerHTML, textContent or innerText?
Use textContent to change plain text, innerText when concerned with display CSS, and innerHTML when you actually need to insert new HTML tags inside.
To Change HTML element content with JavaScript DOM, you have 3 main weapons, but you need to use them at the right time and place:
| Attributes | Features & Usage | Security/Performance Notes |
|---|---|---|
| textContent | Gets or assigns all plain text inside the node, ignoring any HTML tags. | Very safe, highest performance. Should use default. |
| innerText | Giống textContent nhưng có "nhận thức" về CSS. Nó sẽ không lấy các đoạn text bị ẩn bởi display: none. |
A bit slower than textContent because the CSS layout must be calculated. |
| innerHTML | Allows you to get or insert the entire HTML code structure inside the element. | Nguy hiểm! Dễ dính lỗi bảo mật XSS nếu chèn dữ liệu không kiểm soát từ người dùng [4]. |
Changing attributes: setAttribute, getAttribute and the "unexpected" trick
The setAttribute, getAttribute, and removeAttribute methods make it easy to read, write, and safely remove an element's HTML attributes.
Mọi Thuộc tính HTML như src của thẻ ảnh <img> hay href của thẻ link <a> đều có thể bị thay đổi linh hoạt. Bạn dùng getAttribute để xem giá trị hiện tại là gì, setAttribute để gán một giá trị mới, và removeAttribute để xóa hẳn thuộc tính đó đi.
A little tip for you: when working with tags that have a structural meaning on the page, setting the right attributes is important for search engines. You can refer to HTML5 Semantic SEO standard semantic tags to know how to perfectly combine standard HTML structure and attribute update operations through the DOM.
Changing the "appearance" of CSS: ClassList is the real deal, don't just focus on the style attribute
Instead of directly interfering with the inline style attribute, using the classList attribute to add and remove classes will help separate JavaScript logic and CSS interface better.
Nhiều bạn mới thường Thay đổi CSS phần tử HTML bằng JavaScript DOM bằng cách viết mã kiểu element.style.backgroundColor = 'red'. Cách này can thiệp trực tiếp vào Thuộc tính style (inline style), khiến code CSS bị phân mảnh và cực kỳ khó bảo trì về sau.
Thay vào đó, kinh nghiệm xương máu của mình là hãy luôn dùng classList. Với các hàm như classList.add('active'), classList.remove('hidden'), hay classList.toggle('dark-mode'), bạn chỉ việc bật/tắt các class CSS đã được định nghĩa sẵn. Việc này không chỉ giúp code gọn gàng mà còn hỗ trợ rất tốt cho việc Tối ưu CSS cho tốc độ tải trang nhanh. Thậm chí, bằng cách thay đổi class thông minh, bạn hoàn toàn có thể Tạo animation CSS đẹp không cần JavaScript xử lý logic chuyển động phức tạp, giúp trình duyệt render mượt mà hơn rất nhiều.
Add and remove like a magician: Create, insert, and delete elements
Thao tác DOM cho phép bạn sinh ra các phần tử hoàn toàn mới từ hư không và gắn chúng vào trang, hoặc xóa sổ những thành phần dư thừa một cách chủ động.
Việc thao tác với DOM không chỉ là sửa những gì đã có sẵn. Các Phương thức DOM mạnh mẽ còn cho phép bạn thay đổi toàn bộ cấu trúc trang, một kỹ năng bắt buộc khi bạn làm việc với các API trả về dữ liệu JSON và cần hiển thị chúng lên màn hình.
Add elements to the DOM using appendChild
Use document.createElement to create a new element in memory, then use appendChild or insertBefore to attach it to the desired position in the DOM tree.
To Add elements to the DOM using JavaScript, the standard process always includes 3 steps:
- Tạo phần tử: Gọi
document.createElement('div')để tạo ra một thẻ div mới tinh. - Thêm nội dung/thuộc tính: Dùng
textContenthoặcclassListđể trang bị "vũ khí" cho thẻ vừa tạo. - Gắn vào DOM: Dùng appendChild để nhét nó xuống vị trí cuối cùng bên trong một phần tử cha, hoặc insertBefore để chèn nó vào ngay trước một phần tử anh em cụ thể.
Mẹo nâng cao năm 2026: Nếu bạn cần chèn 100 thẻ <li> cùng lúc, đừng dùng appendChild 100 lần vì nó sẽ gây ra hiện tượng Reflow (tính toán lại bố cục) liên tục, làm giật lag trang [5]. Hãy nhóm chúng lại bằng DocumentFragment trước, sau đó mới append cái fragment đó vào DOM một lần duy nhất. Đây là tiêu chuẩn tối ưu hiệu năng hiện nay [5].
Remove DOM elements without a trace with removeChild
The removeChild method allows you to safely remove a child element from its parent element, helping to clean up the interface and free up memory.
The opposite of adding is subtracting. In How to manipulate the DOM in JavaScript?, to Delete a DOM element with JavaScript, the traditional and safest way is to find the parent element, then call removeChild and pass in the child element to be deleted.
Tuy nhiên, ở hầu hết các trình duyệt hiện đại ngày nay, bạn có thể áp dụng cú pháp ngắn gọn hơn rất nhiều. Chỉ cần chọn đúng phần tử đó và gọi trực tiếp lệnh element.remove(), phần tử đó sẽ "bay màu" khỏi trang ngay lập tức mà không cần phải truy xuất ngược lên phần tử cha của nó.
A practical example: Build a simple To-do list
Combining the techniques of selecting, creating, adding, and deleting elements, you can easily build a basic To-do list application with just a few lines of pure JavaScript.
Để hiểu rõ hơn mọi lý thuyết nãy giờ, hãy xem một Ví dụ thao tác DOM JavaScript kinh điển: làm To-do list.
Khi người dùng nhập tên công việc và bấm "Thêm", bạn dùng querySelector lấy giá trị từ ô input. Tiếp theo, dùng createElement tạo một thẻ <li>, gán textContent bằng giá trị vừa lấy. Cuối cùng, gọi appendChild để đưa thẻ <li> đó vào danh sách <ul> đã có sẵn. Thêm một nút "Xóa" bên cạnh mỗi thẻ <li> và gắn lệnh remove() cho nó. Đơn giản vậy thôi!
And don't forget, when you complete the code and prepare to put the application into production, using the tools minify css html js wordpress will help compress your script files, remove excess white space, and help the application load significantly faster.
Last level: Event handling to make the website truly "live"
Event handling is the final step in tying all DOM operations together, helping the website know how to listen and respond when users interact.
A website, no matter how perfectly structured and beautifully styled it is, without User Interaction is just a static picture. Handling DOM events in JavaScript is about bringing life to that picture, turning it into a real application.
Listen for users with addEventListener
The addEventListener method allows you to attach one or more handlers to a specific event (like click, scroll) on a DOM element without fear of overwriting old code.
This is the most modern and standard method to catch DOM Events. You will use addEventListener to tell the browser: "Hey, when this button is 'clicked' or 'hover', please run this code for me".
Điểm tuyệt vời của phương thức này là bạn có thể gắn bao nhiêu hàm vào cùng một sự kiện cũng được, hoàn toàn khắc phục được nhược điểm dễ bị ghi đè của cách dùng thuộc tính onclick cũ kỹ trong HTML. Nếu bạn đang tìm hiểu các cú pháp viết hàm ẩn danh (arrow function) ngắn gọn để dùng trực tiếp trong các event listener này, bài viết tổng hợp ES6 JavaScript tính năng mới cần biết sẽ là một tài liệu cực kỳ hữu ích cho bạn.
What is Event Object and why is it important?
Event Object is an object that contains all detailed information about the event that just occurred, helping you accurately control mouse coordinates, pressed keys or prevent default behavior.
Mỗi khi một sự kiện xảy ra, trình duyệt luôn tự động ném cho hàm xử lý của bạn một món quà vô giá: đó chính là Event Object (thường được viết tắt là e hoặc event).
Nhờ có đối tượng này, bạn có thể dùng e.target để biết chính xác phần tử con nào vừa bị click (rất hữu ích cho kỹ thuật Event Delegation). Hoặc quan trọng hơn, bạn dùng e.preventDefault() để ngăn chặn một form tự động tải lại trang khi người dùng bấm submit, cho phép bạn tự do kiểm tra dữ liệu bằng JavaScript trước khi gửi đi. Nắm vững đối tượng này là bạn đã đạt trình độ thượng thừa trong thao tác DOM rồi đấy.
In retrospect, manipulating the DOM via JavaScript is not as complicated as it sounds. It's simply a series of logical steps: choose exactly what you need, change it as you like, add or subtract structure, and finally respond to user interaction. From changing the color of a line of text to creating a complex Single Page Application, it all starts with these basic methods. Working hard Learning basic JavaScript DOM and practicing continuously will help you have 80% of the core strength to master the front-end profession.
Have you tried applying these DOM JavaScript HTML element manipulation techniques to your personal projects? If you have any problems during the coding process, or encounter an error of not being able to select an element, don't hesitate to leave a comment below, I will help answer it right away!
Lưu ý: Thông tin trong bài viết này chỉ mang tính chất tham khảo. Để có lời khuyên tốt nhất, vui lòng liên hệ trực tiếp với chúng tôi để được tư vấn cụ thể dựa trên nhu cầu thực tế của bạn.