DOM Manipulation In JavaScript

 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. 1. Accessing Elements:

    • To access elements in the DOM, you can use methods like document.getElementById(), document.querySelector(), or document.querySelectorAll().

  2. Example:

  3. // 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, or innerText.

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 the setAttribute() 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 like appendChild() or insertAdjacentElement().

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:


// Changing inline styles
elementById.style.color = 'red';

// Adding/removing CSS classes
elementById.classList.add('highlight');

DOM manipulation in JavaScript provides powerful capabilities for building interactive and dynamic web applications by programmatically interacting with the structure and content of web pages.

Post a Comment

0 Comments