DOM manipulation in JavaScript involves interacting with the Document Object Model (DOM), which represents the structure of an HTML document as a tree-like structure. Through DOM manipulation, you can dynamically update the content, structure, and style of web pages.
Here's an overview of DOM manipulation in JavaScript along with examples:
1. Accessing Elements:
- To access elements in the DOM, you can use methods like
document.getElementById()
,document.querySelector()
, ordocument.querySelectorAll()
. - Example:
- // Accessing an element by ID const elementById = document.getElementById('myElement'); // Accessing an element by class name const elementsByClassName = document.querySelectorAll('.myClass'); // Accessing an element by tag name const elementsByTagName = document.getElementsByTagName('div');
2. Modifying Element Content:
- You can change the content of HTML elements using properties like
textContent
,innerHTML
, orinnerText
.
Example:
// Changing text content elementById.textContent = 'New content'; // Changing HTML content elementById.innerHTML = '<strong>New content</strong>';
3. Modifying Element Attributes:
- You can change attributes like
src
,href
,class
, etc., using thesetAttribute()
method.
Example:
// Changing attribute elementById.setAttribute('class', 'newClass');
4. Creating and Appending Elements:
- You can create new elements using the
createElement()
method and append them to the DOM using methods likeappendChild()
orinsertAdjacentElement()
.
Example:
// Creating a new element const newElement = document.createElement('div'); newElement.textContent = 'New element'; // Appending to an existing element elementById.appendChild(newElement);
5. Event Handling:
- You can attach event listeners to DOM elements using methods like
addEventListener()
to handle user interactions.
Example:
// Adding an event listener elementById.addEventListener('click', () => { console.log('Element clicked'); });
6. Styling Elements:
- You can modify CSS styles of elements using the
style
property or by adding/removing CSS classes.
Example:
0 Comments