javascript dom manipulation guide working with html elements

JavaScript DOM Manipulation: A Practical Guide to Working With HTML Elements

SEO BRIEF — delete before publish | KW: javascript dom manipulation | Slug: /javascript-dom-manipulation/ | Secondary: javascript click button, call javascript function from html, javascript create div, javascript get elements by class name, run javascript on page load

The DOM (Document Object Model) is the browser’s representation of an HTML page as a tree of objects that JavaScript can read and modify. Every button click, form submission, style change, and dynamic content update you see on a web page is JavaScript manipulating the DOM. This guide covers the operations you will use on almost every project.

Selecting Elements

document.getElementById(‘id’) selects a single element by its ID attribute. Returns the element or null if not found.

document.querySelector(‘.class’) selects the first element matching a CSS selector. document.querySelectorAll(‘.class’) returns a NodeList of all matching elements. These two methods handle almost every selection need with the full power of CSS selectors.

document.getElementsByClassName(‘class’) and document.getElementsByTagName(‘tag’) return live HTMLCollections that update as the DOM changes. querySelectorAll returns a static NodeList that does not update. For most use cases, querySelector and querySelectorAll are clearer and more versatile.

Modifying Element Content and Attributes

javascript dom manipulation guide working with html elements
JavaScript DOM manipulation and HTML element interaction

element.innerHTML sets or gets the HTML content inside an element. element.textContent sets or gets the text content without parsing HTML — safer for user-supplied content because it prevents XSS injection.

element.setAttribute(‘attr’, ‘value’) sets an attribute. element.getAttribute(‘attr’) reads it. element.src, element.href, element.value, and similar properties provide direct access to common attributes without setAttribute.

Creating and Inserting Elements

document.createElement(‘div’) creates a new element. Assign its content and attributes, then insert it: parent.appendChild(newElement) adds it as the last child. parent.insertBefore(newElement, referenceElement) inserts it before a specific child.

element.insertAdjacentHTML(‘beforeend’, ‘

text

‘) is a faster alternative for inserting HTML strings at specific positions relative to an element without replacing the entire innerHTML.

Handling Events

element.addEventListener(‘click’, function(event) {}) attaches an event listener. The event object contains information about the interaction — target element, mouse position, key pressed. Use removeEventListener with the same function reference to detach it.

Event delegation: instead of attaching listeners to every child element, attach one listener to the parent and check event.target. This is more efficient and works for elements added to the DOM after the listener is attached.

Running Code on Page Load

document.addEventListener(‘DOMContentLoaded’, function() {}) runs code after the HTML is fully parsed but before images and stylesheets finish loading. This is the correct place to initialize DOM manipulation that does not depend on images.

window.addEventListener(‘load’, function() {}) runs after everything — HTML, stylesheets, images, fonts — has loaded. Use this when your code depends on element dimensions that require images to be loaded first.

Changing Styles and Classes

element.classList.add(‘class’), element.classList.remove(‘class’), and element.classList.toggle(‘class’) manage CSS classes. element.classList.contains(‘class’) checks if a class is present.

element.style.backgroundColor = ‘#ff0000’ sets inline styles directly. For coordinated visual changes, adding and removing CSS classes is cleaner — the styles live in the stylesheet and the JavaScript just controls which class is active.

Frequently Asked Questions

What is the difference between innerHTML and textContent? innerHTML parses its value as HTML and can introduce XSS vulnerabilities if set to user-supplied content. textContent treats everything as literal text. Use textContent when setting user data, innerHTML when you need to insert HTML structure.

How do I call a JavaScript function from an HTML button? Add an onclick attribute: button onclick=’myFunction()’ or attach an event listener in JavaScript: document.querySelector(‘button’).addEventListener(‘click’, myFunction). The event listener approach is preferred — it keeps behavior out of HTML.

How do I set a CSS variable from JavaScript? document.documentElement.style.setProperty(‘–my-color’, ‘#ff0000’) sets a CSS custom property on the root element, making it available throughout the document.

Why does my DOM manipulation code run before the elements exist? The script is executing before the DOM is built. Add the defer attribute to the script tag, move the script to the end of the body, or wrap the code in a DOMContentLoaded event listener.