5 min read
•Question 19 of 50easyHow to Manipulate the DOM in JavaScript?
Understanding DOM selection and manipulation.
What You'll Learn
- Selecting elements
- Modifying elements
- Creating and removing elements
Selecting Elements
code.jsJavaScript
// By ID
const el = document.getElementById('myId');
// By class
const els = document.getElementsByClassName('myClass');
// By tag
const divs = document.getElementsByTagName('div');
// Query selector (single)
const first = document.querySelector('.myClass');
// Query selector (all)
const all = document.querySelectorAll('.myClass');Modifying Elements
code.jsJavaScript
const el = document.querySelector('#myElement');
// Content
el.textContent = 'New text';
el.innerHTML = '<span>HTML content</span>';
// Attributes
el.setAttribute('data-id', '123');
el.getAttribute('data-id');
el.removeAttribute('data-id');
// Classes
el.classList.add('active');
el.classList.remove('hidden');
el.classList.toggle('visible');
el.classList.contains('active');
// Styles
el.style.color = 'red';
el.style.backgroundColor = 'blue';Creating Elements
code.jsJavaScript
// Create element
const div = document.createElement('div');
div.textContent = 'Hello';
div.classList.add('greeting');
// Append to DOM
document.body.appendChild(div);
parent.insertBefore(div, referenceElement);
parent.append(div); // Also accepts strings
parent.prepend(div);Removing Elements
code.jsJavaScript
element.remove();
parent.removeChild(child);