JavaScript Event Handling: 5 Quick Wins
Learn JavaScript event handling with 5 steps: addEventListener, event types, propagation, delegation, and cleanup.
Read more →Learn modifying DOM elements with 5 techniques: text, attributes, styles, classes, and structure. Build dynamic, interactive web pages today.
Modifying DOM elements is how you make a static page responsive to user interaction, data and time. After you select an element, you can essentially change nearly anything about it.
Have you ever clicked a button that caused some text to show up? Have you changed themes and seen colors alter? Or have you submitted a form and received some kind of “success” message? In each of those cases, JavaScript was dynamically modifying the DOM elements. This is NOT a fixed snapshot. The DOM is a live tree that you can shape however you’d like.
If you’re new to modifying DOM elements, I’m sure you’ve worried about messing something up. Fortunately, the browser provides easy to use, safe tools for modifying DOM elements. You modify what you need and the page updates immediately. Here we’ll cover five basic techniques you will find yourself using continually to modify DOM elements:
Changing what the users see is the most typical modification. You have two primary tools: textContent and innerHTML.
textContent is the safest, fastest option for modifying the DOM elements for plain text. This removes any HTML tags within an element. It would be ideal for updating a score, a status message, or a username. Because it doesn’t parse any HTML it is impervious to cross-site scripting attacks.
innerHTML is a lot more powerful, but riskier. This takes a string of characters as HTML and creates the necessary DOM structure. Using this you can easily place complex objects like lists or tables into an area of the DOM. However, if you’re inserting content supplied by users, attackers may attempt to embed malicious script. Always sanitize any untrusted data prior to utilizing innerHTML for modifying DOM elements.
Form inputs utilize the value property. Getting input.value returns what the user entered and setting it modifies the contents of the field. This is crucial for resetting forms, providing default fields or verifying user input.
Unless you absolutely require HTML to accomplish something, favor using textContent for modifying text and HTML in the DOM. It is safer, quicker and less likely to be misused.
Each HTML element has attributes – src, href, alt, disabled, data-*, etc. You can both read from and write to these attributes using standard DOM APIs.
Your primary tools for working with attributes are getAttribute(), setAttribute() and removeAttribute(). For example, you can change an image src attribute on the fly upon clicking a thumbnail. You can change the destination URL of a hyperlink depending on a user selection. You can disable a button once it has been clicked to avoid submitting it twice. All three of these activities involve modifying DOM elements at the attribute level.
There are some attributes that have direct property shortcuts available. For example, img.src works identically to calling img.getAttribute(“src”). That being said, using a shortcut is usually a little shorter and clearer when modifying DOM elements.
The setAttribute() function is handy when an attribute name includes a hyphen (-), or when you wish to be explicit regarding the attribute name. Boolean attributes (such as disabled, checked or readonly) should be handled by setting their respective boolean values (.disabled=true or .checked=false). This is a little clearer than setting the attribute string manually and is a common technique used while modifying DOM elements.
You can change the look of an element by adjusting its style property. This directly adjusts the inline style of the element, effectively overriding any CSS applied to the element.
For example, element.style.backgroundColor=’blue’; will colorize the background blue. Similarly, element.style.fontSize=’20px’; will increase the font size. When accessing properties of an object in JavaScript, they convert from kebab-case (background-color) to camelCase (backgroundColor). Although convenient and easy to understand, there are several downsides to modifying an element’s inline style. Most notably, inline styles are difficult to support long term and override.
A far superior alternative for modifying the presentation of an element is to change CSS classes rather than inline styles. As long as you have defined a style rule in your stylesheet, you can add, remove or toggle classes using JavaScript. By doing so, you will keep your presentation logic separate from your behavior logic.
The classList API provides add/remove/toggle/contains functions. For example, element.classList.add(‘highlight’); will apply a predefined highlight style to an element. Similarly, element.classList.toggle(‘dark-mode’); will either enable or disable the dark mode theme on an element. Not only is this approach cleaner and more efficient, it is easier to debug when modifying DOM elements.
Modify an element’s inline style when you must include dynamic information that cannot be represented with classes (i.e. animate an element based on mouse movement).
In addition to simply defining appearance with CSS classes, modifying the DOM elements by applying classes defines component states.
For example, a drop down menu might have an open state denoted by a class called .is-open. Upon adding that class, the menu opens up. Removing that class causes the menu to hide again. An accordion item might use .active to denote whether it shows its content. A form field might use .has-error to display a red border around its content. Each of these represents a case of modifying the DOM elements by toggling state classes.
Utilizing classes for representing state is beneficial in keeping your CSS very simple and your JavaScript code concise. Rather than having scattered throughout your codebase various places where you’re modifying the appearance of things, you merely toggle on/off classes which represent states of components in your application.
All modern browsers support classList methods. You could also replace the entire string of className attributes; however, this approach is error prone. Utilize classList when performing individual operations for modifying DOM elements.
Be consistent when modifying DOM elements with classes; assign clear descriptive names to your state classes (i.e., .is-visible, .has-error, .theme-dark) and document what each represents.
Sometimes modifying DOM elements isn’t sufficient; sometimes you need to completely add new elements to the DOM or delete existing ones altogether. This is how you generate dynamic lists, modal dialog boxes or endless scrolling feeds.
To create a new element, first create it with document.createElement(“div”); Next you’ll populate its properties, text, attributes or even nest other elements inside it. Finally, insert it into the DOM using appendChild(), insertBefore(), prepend() or append().
append() can take multiple nodes or strings and append all of them together at once. For example: parent.append(newElement,”someText”,anotherElement); inserts everything at the end. prepend() appends at the beginning. Both of these are important for structurally modifying DOM elements.
To delete an element, call its remove(); Method. This is arguably the cleanest way. Older methods such as removeChild() still work fine but are more cumbersome.
You can also replace an existing element with replaceChild() or use insertAdjacentHTML() to insert an HTML string at a given location relative to an existing element. Be careful with insertAdjacentHTML(); Like innerHTML() it too parses the inserted string as HTML so you must sanitize any user supplied content.
Remember to clean-up when structurally modifying the DOM. Any event listener attached to an element deleted with remove() will be garbage collected along with that deleted element (as long as no other references remain). This prevents memory leaks.
These five modification techniques – modifying text/content/html, modifying attributes, modifying styles, toggling classes, creating/removing elements, provide full control over how you modify DOM elements.
Build small interactions initially. Develop a button that changes the text of a paragraph. Develop another button that toggles a highlight class onto/from an element. Build a list in which you can add/delete entries. Then develop larger interactions combining these techniques such as a simple tabbed interface or light/dark theme switcher.
The more experience you gain modifying DOM elements the more confidence you’ll feel toward making dynamic changes and viewing the DOM as your own canvas.
Below is a brief reference guide designed to help facilitate your learning process when practicing modifying DOM elements.
For further study resources regarding these topics please visit JavaScript.info’s documentation regarding modifying documents including several examples illustrating best practices for modifying the document.
Learning how to modify DOM elements enables the full potential of JavaScript programming. No longer are you merely able to view/read pages; now you’re capable of manipulating pages in real-time based on user activity/input/data/time and more! Learn these 5 basic techniques and begin developing truly dynamic interactive Web Applications!
New to HTML? Start Here: HTML Tutorial for Beginners: Your Complete Introduction to HTML Basics
New to CSS? Start Here: CSS Introduction: Master 5 Core Concepts Easily
New to JavaScript? JavaScript Introduction: 5 Proven Steps to Learn JS
Practice what you learned
Reading is step one. Open this lesson's starter code in the editor, finish it, and you've really learned it.
Learn JavaScript event handling with 5 steps: addEventListener, event types, propagation, delegation, and cleanup.
Read more →Master JavaScript form validation with 5 techniques: required fields, regex, password checks, real‑time feedback, and custom rules.
Read more →Master JavaScript strings and string methods with 5 essential techniques: creation, searching, extraction, transformation, and template literals.
Read more →Arm yourself with step by step tutorials, expert tips, and insider tools to conquer any coding project - subscribe now.