Essential JavaScript code snippets for working with the Document Object Model. Copy, paste, and modify for your projects.
No snippets found matching your search.
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 all elements matching a CSS selector (returns NodeList)
const elements = document.querySelectorAll('.class-name');
elements.forEach(el => {
console.log(el);
});
Select element by its ID attribute (faster than querySelector)
const element = document.getElementById('my-id');
// No # symbol needed!
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));
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);
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
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 an element from the DOM
const element = document.querySelector('.remove-me');
element.remove();
// Or: element.parentNode.removeChild(element);
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');
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';
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';
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 = '';
Add one or more classes to an element
const element = document.querySelector('.box');
element.classList.add('active');
element.classList.add('highlighted', 'featured');
Remove one or more classes from an element
const element = document.querySelector('.box');
element.classList.remove('active');
element.classList.remove('highlighted', 'featured');
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 an element has a specific class
const element = document.querySelector('.box');
if (element.classList.contains('active')) {
console.log('Element is active');
}
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
});
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 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);
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);
});
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 all child elements (not text nodes)
const parent = document.querySelector('.parent');
const children = parent.children; // HTMLCollection
const firstChild = parent.firstElementChild;
const lastChild = parent.lastElementChild;
Access next or previous sibling elements
const element = document.querySelector('.current');
const nextSibling = element.nextElementSibling;
const prevSibling = element.previousElementSibling;
Find nearest ancestor matching a selector
const element = document.querySelector('.nested');
const card = element.closest('.card');
const container = element.closest('[data-container]');