Expanded Dom Cheat Sheet
Expanded Dom Cheat Sheet
----------------------------------------
1. SELECT ELEMENTS
- By ID:
const title = document.getElementById('title');
- By class:
const items = document.getElementsByClassName('item');
- By tag:
const paragraphs = document.getElementsByTagName('p');
----------------------------------------
2. CHANGE TEXT OR HTML
Example:
document.getElementById('title').textContent = 'Welcome!';
----------------------------------------
3. CHANGE STYLES
element.style.color = 'blue';
element.style.fontSize = '20px';
Example:
button.style.backgroundColor = 'green';
----------------------------------------
4. MANAGE CLASSES
element.classList.add('active');
element.classList.remove('hidden');
element.classList.toggle('dark-mode');
Example:
title.classList.toggle('highlight');
----------------------------------------
5. ADD EVENT LISTENERS
element.addEventListener('click', function() {
alert('Button clicked!');
});
Example:
button.addEventListener('click', () => {
console.log('You clicked the button!');
});
----------------------------------------
6. CREATE AND ADD ELEMENTS
----------------------------------------
7. REMOVE ELEMENTS
----------------------------------------
8. TRAVERSE THE DOM
element.parentElement;
element.children;
element.nextElementSibling;
element.previousElementSibling;
Example:
const parent = item.parentElement;
const firstChild = parent.children[0];
----------------------------------------
9. FORM INPUTS
----------------------------------------
10. ATTRIBUTES
element.setAttribute('src', 'image.jpg');
element.getAttribute('href');
element.removeAttribute('disabled');
Example:
document.querySelector('img').setAttribute('alt', 'Picture of a cat');
----------------------------------------
11. WORKING WITH LOCAL STORAGE
localStorage.setItem('key', 'value');
const value = localStorage.getItem('key');
localStorage.removeItem('key');
Example:
localStorage.setItem('username', 'john123');
----------------------------------------
12. FETCH API (Basic)
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data));
----------------------------------------
Tip:
Place your <script> tag at the end of <body> or wrap JS code like this:
window.onload = function() {
// your code here
};