DOM Manipulation Snippets

Essential JavaScript code snippets for working with the Document Object Model. Copy, paste, and modify for your projects.

No snippets found matching your search.

Selecting Elements

Select Single Element

Select the first element matching a CSS selector

const element = document.querySelector('.class-name');
const byId = document.querySelector('#my-id');
const byTag = document.querySelector('div');

Select Multiple Elements

Select all elements matching a CSS selector (returns NodeList)

const elements = document.querySelectorAll('.class-name');
elements.forEach(el => {
  console.log(el);
});

Get Element by ID

Select element by its ID attribute (faster than querySelector)

const element = document.getElementById('my-id');
// No # symbol needed!

Get Elements by Class

Select elements by class name (returns HTMLCollection)

const elements = document.getElementsByClassName('class-name');
// Convert to array for array methods
Array.from(elements).forEach(el => console.log(el));

Creating & Modifying Elements

Create New Element

Create a new element and add it to the DOM

const div = document.createElement('div');
div.textContent = 'Hello World';
div.className = 'my-class';
document.body.appendChild(div);

Change Text Content

Update the text inside an element (safer than innerHTML)

const element = document.querySelector('.title');
element.textContent = 'New Title';
// textContent is safer than innerHTML for plain text

Change HTML Content

Update HTML content (use with caution for security)

const container = document.querySelector('.container');
container.innerHTML = '<h2>Title</h2><p>Content</p>';
// Warning: Be careful with user input!

Remove Element

Remove an element from the DOM

const element = document.querySelector('.remove-me');
element.remove();
// Or: element.parentNode.removeChild(element);

Attributes & Properties

Get/Set Attributes

Work with HTML attributes

const img = document.querySelector('img');
// Get attribute
const src = img.getAttribute('src');
// Set attribute
img.setAttribute('alt', 'Description');
// Remove attribute
img.removeAttribute('title');

Data Attributes

Access custom data-* attributes

// HTML: <div data-user-id="123" data-role="admin">
const element = document.querySelector('div');
const userId = element.dataset.userId; // "123"
const role = element.dataset.role; // "admin"
element.dataset.status = 'active';

Modify Inline Styles

Change element styles directly (use classes when possible)

const element = document.querySelector('.box');
element.style.backgroundColor = '#4facfe';
element.style.padding = '20px';
element.style.borderRadius = '10px';

Get/Set Input Values

Work with form input values

const input = document.querySelector('input');
// Get value
const value = input.value;
// Set value
input.value = 'New text';
// Clear value
input.value = '';

Working with Classes

Add Class

Add one or more classes to an element

const element = document.querySelector('.box');
element.classList.add('active');
element.classList.add('highlighted', 'featured');

Remove Class

Remove one or more classes from an element

const element = document.querySelector('.box');
element.classList.remove('active');
element.classList.remove('highlighted', 'featured');

Toggle Class

Toggle a class on/off (perfect for show/hide)

const element = document.querySelector('.menu');
element.classList.toggle('open');
// Force add or remove
element.classList.toggle('visible', true); // Add
element.classList.toggle('visible', false); // Remove

Check if Class Exists

Check if an element has a specific class

const element = document.querySelector('.box');
if (element.classList.contains('active')) {
  console.log('Element is active');
}

Event Handling

Add Click Event

Add a click event listener to an element

const button = document.querySelector('button');
button.addEventListener('click', (event) => {
  console.log('Button clicked!');
  event.preventDefault(); // For links/forms
});

Event Delegation

Handle events on multiple children efficiently

const list = document.querySelector('ul');
list.addEventListener('click', (event) => {
  if (event.target.tagName === 'LI') {
    console.log('List item clicked:', event.target.textContent);
  }
});

Remove Event Listener

Remove a previously added event listener

const handleClick = (event) => {
  console.log('Clicked!');
};
const button = document.querySelector('button');
button.addEventListener('click', handleClick);
// Later...
button.removeEventListener('click', handleClick);

Multiple Event Types

Add the same listener to multiple event types

const input = document.querySelector('input');
const handleInput = (event) => {
  console.log('Input changed:', event.target.value);
};
['input', 'change', 'blur'].forEach(eventType => {
  input.addEventListener(eventType, handleInput);
});

DOM Traversal

Get Parent Element

Access the parent of an element

const child = document.querySelector('.child');
const parent = child.parentElement;
// Or get specific parent
const container = child.closest('.container');

Get Children

Get all child elements (not text nodes)

const parent = document.querySelector('.parent');
const children = parent.children; // HTMLCollection
const firstChild = parent.firstElementChild;
const lastChild = parent.lastElementChild;

Get Siblings

Access next or previous sibling elements

const element = document.querySelector('.current');
const nextSibling = element.nextElementSibling;
const prevSibling = element.previousElementSibling;

Find Closest Ancestor

Find nearest ancestor matching a selector

const element = document.querySelector('.nested');
const card = element.closest('.card');
const container = element.closest('[data-container]');