andrewolson1986
andrewolson1986 20h ago β€’ 0 views

Sample code for Javascript DOM Manipulation methods

Hey there! πŸ‘‹ Learning JavaScript DOM manipulation can feel a bit daunting at first, but it's super useful for making websites interactive. I'm diving into this topic myself, and I'm looking for some clear, practical code examples. Anyone have some good snippets to share? Thanks! πŸ™
πŸ’» Computer Science & Technology

1 Answers

βœ… Best Answer
User Avatar
timothy.warren Dec 28, 2025

πŸ“š Understanding the Document Object Model (DOM)

The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects; that way, programming languages can interact with the page.

πŸ“œ A Brief History of DOM

The DOM emerged in the late 1990s as web browsers became more widespread. Netscape and Microsoft developed competing versions of JavaScript, leading to incompatibilities. The World Wide Web Consortium (W3C) standardized the DOM to ensure consistency across browsers. This standardization allowed developers to create web applications that worked predictably, regardless of the browser used.

πŸ”‘ Key Principles of DOM Manipulation

  • 🌳 DOM Tree: The DOM represents an HTML document as a tree structure, where each HTML element, attribute, or text is a node in the tree.
  • 🎯 Node Selection: Selecting specific elements in the DOM is crucial for manipulation. Methods like `getElementById`, `getElementsByClassName`, and `querySelector` are used for this purpose.
  • ✨ Dynamic Updates: The power of DOM manipulation lies in its ability to dynamically update the content, attributes, and styles of HTML elements without reloading the page.
  • πŸ‘‚ Event Handling: Attaching event listeners to DOM elements allows you to respond to user interactions, such as clicks, mouseovers, and form submissions.

πŸ’» Sample Code Examples

πŸ“Œ Selecting Elements

  • πŸ†” `getElementById()`: Retrieves an element by its unique ID.
  • 
            const element = document.getElementById('myElement');
            console.log(element);
            
  • 🏷️ `getElementsByClassName()`: Retrieves all elements with a specified class name. Returns an HTMLCollection.
  • 
            const elements = document.getElementsByClassName('myClass');
            console.log(elements);
            
  • #️⃣ `querySelector()`: Returns the first element that matches a specified CSS selector.
  • 
            const element = document.querySelector('.myClass');
            console.log(element);
            
  • πŸ’― `querySelectorAll()`: Returns all elements that match a specified CSS selector. Returns a NodeList.
  • 
            const elements = document.querySelectorAll('div > p');
            console.log(elements);
            

✏️ Modifying Elements

  • πŸ“ƒ `innerHTML`: Gets or sets the HTML markup contained within an element.
  • 
            const element = document.getElementById('myElement');
            element.innerHTML = '

    New content!

    ';
  • πŸ–‹οΈ `textContent`: Gets or sets the text content of an element.
  • 
            const element = document.getElementById('myElement');
            element.textContent = 'New text content!';
            
  • 🎨 `setAttribute()`: Sets the value of an attribute on the specified element.
  • 
            const element = document.getElementById('myElement');
            element.setAttribute('class', 'newClass');
            
  • πŸ—‘οΈ `removeAttribute()`: Removes a specified attribute from an element.
  • 
            const element = document.getElementById('myElement');
            element.removeAttribute('class');
            
  • βž• `classList.add()`: Adds one or more class names to an element.
  • 
            const element = document.getElementById('myElement');
            element.classList.add('newClass', 'anotherClass');
            
  • βž– `classList.remove()`: Removes one or more class names from an element.
  • 
            const element = document.getElementById('myElement');
            element.classList.remove('newClass');
            

βž• Creating and Adding Elements

  • ✨ `createElement()`: Creates a new element node.
  • 
            const newElement = document.createElement('div');
            
  • πŸ“ `createTextNode()`: Creates a new text node.
  • 
            const newText = document.createTextNode('Hello, world!');
            
  • 🎁 `appendChild()`: Adds a node to the end of the list of children of a specified parent node.
  • 
            const parentElement = document.getElementById('myElement');
            const newElement = document.createElement('p');
            newElement.textContent = 'This is a new paragraph.';
            parentElement.appendChild(newElement);
            
  • 🌱 `insertBefore()`: Inserts a node before a specified child node of a parent node.
  • 
            const parentElement = document.getElementById('myElement');
            const newElement = document.createElement('p');
            newElement.textContent = 'This is a new paragraph.';
            const referenceElement = document.getElementById('existingElement');
            parentElement.insertBefore(newElement, referenceElement);
            
  • πŸ’₯`removeChild()`: Removes a child node from the DOM.
  • 
             const parentElement = document.getElementById('myElement');
             const childElement = document.getElementById('childElement');
             parentElement.removeChild(childElement);
             

πŸ‘‚ Event Handling

  • πŸ–±οΈ `addEventListener()`: Attaches an event listener to an element.
  • 
            const button = document.getElementById('myButton');
            button.addEventListener('click', function() {
                alert('Button clicked!');
            });
            

πŸ’‘ Best Practices

  • ⚑ Optimize Selectors: Use specific selectors like IDs instead of broad selectors like class names to improve performance.
  • πŸ›‘οΈ Avoid Memory Leaks: Remove event listeners when they are no longer needed to prevent memory leaks.
  • 🌐 Cross-Browser Compatibility: Test your code in different browsers to ensure compatibility.
  • ♻️ Batch Updates: When making multiple updates to the DOM, batch them together to minimize reflows and repaints.

Conclusion

JavaScript DOM manipulation is a fundamental skill for web developers. By understanding how to select, modify, create, and add elements dynamically, you can create interactive and engaging web applications. Always follow best practices to ensure your code is efficient, maintainable, and compatible across different browsers.

Join the discussion

Please log in to post your answer.

Log In

Earn 2 Points for answering. If your answer is selected as the best, you'll get +20 Points! πŸš€