JS DOM Manipulation
JavaScript provides a variety of methods for interacting with the Document Object Model (DOM). These methods provide powerful tools for manipulating the HTML structure and styles dynamically in web applications.
Tutorials:
Selecting Elements
document.getElementById(id): Selects an element by its ID.document.getElementsByClassName(className): Selects a collection of elements by their class name.document.getElementsByTagName(tagName): Selects a collection of elements by their tag name.document.querySelector(selector): Selects the first element that matches a CSS selector.document.querySelectorAll(selector): Selects all elements that match a CSS selector.
Creating and Inserting Elements
document.createElement(tagName): Creates a new element of the specified type.element.appendChild(child): Adds a child element to the specified parent element.element.insertBefore(newNode, referenceNode): Inserts a new node before a reference node as a child of a specified parent node.element.replaceChild(newChild, oldChild): Replaces an old child with a new child in a specified parent.
Modifying Elements
element.setAttribute(name, value): Sets an attribute on the specified element.element.getAttribute(name): Gets the value of the specified attribute.element.removeAttribute(name): Removes the specified attribute from the element.element.classList.add(className): Adds a class to the element.element.classList.remove(className): Removes a class from the element.element.innerHTML: Gets or sets the HTML content of an element.element.textContent: Gets or sets the text content of an element.
Event Handling
element.addEventListener(event, function): Attaches an event handler to the specified element.element.removeEventListener(event, function): Removes an event handler from the specified element.
Traversing the DOM
element.parentNode: Gets the parent node of the specified element.element.childNodes: Gets a live NodeList of child nodes of the specified element.element.firstChild / element.lastChild: Gets the first or last child of the specified element.element.nextSibling / element.previousSibling: Gets the next or previous sibling of the specified element.
Styling Elements
element.style: Accesses the inline style of the element.element.className: Gets or sets the CSS class of the element.