To access and modify HTML document elements in JavaScript, you can use the Document Object Model (DOM). The DOM is a programming interface for web documents, providing a structured representation that can be manipulated using JavaScript.
Accessing Elements:
By ID:
// Access an element by its ID
var elementById = document.getElementById('yourElementId');
By Class Name:
// Access elements by their class name (returns a NodeList)
var elementsByClass = document.getElementsByClassName('yourClassName');
By Tag Name:
// Access elements by their tag name (returns a NodeList)
var elementsByTag = document.getElementsByTagName('yourTagName');
By CSS Selector:
// Access elements using a CSS selector (returns the first matching element)
var elementBySelector = document.querySelector('yourSelector');
// Access elements using a CSS selector (returns a NodeList of all matching elements)
var elementsBySelectorAll = document.querySelectorAll('yourSelector');
Modifying Elements:
// Change the text content of an element
elementById.textContent = 'New Text Content';
// Change the HTML content of an element
elementById.innerHTML = '<p>New HTML Content</p>';
// Change the value of an attribute
elementById.setAttribute('src', 'new-source.jpg');
// Add a class to an element
elementById.classList.add('newClass');
// Remove a class from an element
elementById.classList.remove('oldClass');
// Append a new element to an existing element
var newElement = document.createElement('div');
newElement.textContent = 'New Element';
elementById.appendChild(newElement);
// Remove an element
elementById.removeChild(newElement);
These are basic examples, and the DOM provides a rich set of methods and properties for more advanced manipulation of HTML documents. Always be mindful of browser compatibility and consider using libraries like jQuery for simplifying complex DOM manipulations.
Accessing and modifying HTML document elements in JavaScript