Here are some common DOM methods used in web development:
-
document.getElementById(id): Retrieves an element by its unique ID.const element = document.getElementById('myElement'); -
document.getElementsByClassName(className): Returns a live HTMLCollection of elements with the specified class name.const elements = document.getElementsByClassName('myClass'); -
document.getElementsByTagName(tagName): Returns a live HTMLCollection of elements with the specified tag name.const elements = document.getElementsByTagName('div'); -
document.querySelector(selector): Returns the first element that matches the specified CSS selector.const element = document.querySelector('.myClass'); -
document.querySelectorAll(selector): Returns a static NodeList of all elements that match the specified CSS selector.const elements = document.querySelectorAll('div.myClass'); -
element.appendChild(child): Adds a new child node to the specified parent node.const newElement = document.createElement('p'); document.body.appendChild(newElement); -
element.removeChild(child): Removes a specified child node from the parent node.const child = document.getElementById('childElement'); document.body.removeChild(child); -
element.setAttribute(attributeName, value): Sets the value of an attribute on the specified element.element.setAttribute('class', 'newClass'); -
element.style.property = value: Modifies the inline style of an element.element.style.color = 'red';
These methods are fundamental for manipulating the DOM and creating dynamic web applications.
