1. Selecting Elements
- Select by ID:
const element = document.getElementById('myId');
- Select by Class Name:
const elements = document.getElementsByClassName('myClass'); // returns a live HTMLCollection
- Select by Tag Name:
const elements = document.getElementsByTagName('div'); // returns a live HTMLCollection
- Select using Query Selector:
const element = document.querySelector('.myClass'); // selects the first matching element
- Select all using Query Selector All:
const elements = document.querySelectorAll('.myClass'); // returns a static NodeList
2. Creating and Inserting Elements
- Create a new element:
const newElement = document.createElement('div');
- Add text to the new element:
newElement.textContent = 'Hello, World!';
- Insert into the DOM:
document.body.appendChild(newElement); // appends to the end of the body
- Insert before a specific element:
const referenceElement = document.getElementById('myId');
document.body.insertBefore(newElement, referenceElement);
3. Modifying Elements
- Change an element's text:
element.textContent = 'New Text';
- Change an element's HTML:
element.innerHTML = '<strong>New HTML Content</strong>';
- Change styles:
element.style.color = 'red';
element.style.backgroundColor = 'blue';
- Change attributes:
element.setAttribute('href', 'https://example.com');
4. Removing Elements
- Remove an element:
const elementToRemove = document.getElementById('myId');
elementToRemove.parentNode.removeChild(elementToRemove);
5. Event Handling
- Add an event listener:
element.addEventListener('click', function() {
alert('Element clicked!');
});
- Remove an event listener:
const handleClick = () => {
alert('Element clicked!');
};
element.addEventListener('click', handleClick);
element.removeEventListener('click', handleClick);
6. Traversing the DOM
- Parent Node:
const parent = element.parentNode;
- Child Nodes:
const children = element.childNodes; // includes all child nodes (text, comments, etc.)
- First Child:
const firstChild = element.firstChild;
- Last Child:
const lastChild = element.lastChild;
- Next Sibling:
const nextSibling = element.nextSibling;
- Previous Sibling:
const previousSibling = element.previousSibling;
Happy coding!
Top comments (0)