JavaScript DOM Manipulation

A practical guide to manipulating the Document Object Model (DOM).

Introduction

DOM manipulation is the core of web development. It allows you to dynamically update and interact with web pages. We'll cover essential techniques like selecting elements, modifying attributes, and creating new elements.

Selecting Elements

Element Selection: Use selectors to target specific HTML elements.

Example: `document.querySelector('h1')` selects the first

tag.

Example: `document.getElementsByClassName('my-class')` retrieves all elements with the class 'my-class'.

Example: `document.querySelectorAll('div.container > p')` selects all paragraphs within

s with class 'container' that are direct children of elements.

Modifying Attributes

Attribute Modification: Alter attributes like 'src', 'href', 'class', and 'style'.

Example: `document.getElementById('my-div').setAttribute('src', 'https://example.com/image.jpg')` sets the source of the div.

Example: `document.getElementsByClassName('my-class').style.color = 'red';` changes the color of all elements with the class 'my-class'.

Creating New Elements

New Element Creation: Use `createElement()` to create new HTML elements.

Example: `let newDiv = document.createElement('div');` creates a new div element.

Example: `newDiv.textContent = 'Hello, DOM!';` sets the text content of the div.

Advanced Techniques (Example: Event Handling)

Event Handling: Listen for events like `click`, `mouseover`, and `keydown` to trigger actions.

Example: `document.addEventListener('click', function(event) { console.log('You clicked!'); });` listens for clicks and logs a message.