DOM Manipulation in JavaScript
Shashank Kanojia
Full Stack .NET Developer | Expertise in C#, ASP.NET Core, MVC, SQL Server and React
DOM (Document Object Model) manipulation in JavaScript is a crucial aspect of web development, allowing you to interact with and manipulate the structure and content of HTML and XML documents dynamically. Here's a basic overview of DOM manipulation in JavaScript:
Accessing DOM Elements:
let element = document.getElementById('elementId');
let elements = document.getElementsByClassName('className');
let elements = document.getElementsByTagName('tagName');
let element = document.querySelector('selector');
let elements = document.querySelectorAll('selector');
Manipulating Element Content:
element.innerHTML = 'New content';
element.innerText = 'New text';
element.textContent = 'New text content';
element.setAttribute('attributeName', 'attributeValue');
element.style.property = 'value';
let newElement = document.createElement('tagName');
parentElement.appendChild(newElement); // Append
parentElement.removeChild(childElement); // Remove
element.addEventListener('event', function() {
// Your event handling code
});
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Manipulation</title>
<style>
.highlight {
color: blue;
font-weight: bold;
}
</style>
</head>
<body>
<h1 id="mainHeading">Hello, DOM!</h1>
<button id="changeTextButton">Change Text</button>
<script>
document.addEventListener('DOMContentLoaded', function() {
let heading = document.getElementById('mainHeading');
let button = document.getElementById('changeTextButton');
button.addEventListener('click', function() {
heading.innerText = 'Text Changed!!!!';
heading.classList.add('highlight');
});
});
</script>
</body>
</html>
In this example, clicking the button changes the text of the heading and adds a CSS class to highlight it. The script is placed at the end of the body to ensure the DOM elements are available when the script runs.