Dom Manipulation
DOM (Document Object Model) manipulation is a technique used in web development to interact with HTML and XML documents dynamically. In the context of client-side scripting languages like JavaScript, DOM manipulation allows you to change the structure, style, and content of a web page in response to user actions or events.
Here's a basic example of DOM manipulation using JavaScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Manipulation Example</title>
</head>
<body>
<h1 id="myHeading">Hello, World!</h1>
<button onclick="changeText()">Change Text</button>
<script>
function changeText() {
// Accessing the element with id 'myHeading'
var heading = document.getElementById("myHeading");
// Modifying the content of the element
heading.innerHTML = "Hello, DOM!";
}
</script>
</body>
</html>
In this example:
There is an HTML heading (
<h1>
) element with the id "myHeading" and initial text "Hello, World!".There is a button with an
onclick
attribute that calls thechangeText
JavaScript function when clicked.The JavaScript function
changeText
uses thedocument.getElementById
method to access the element with the id "myHeading" and then modifies its content using theinnerHTML
property.
This is a simple example, and there are many other DOM manipulation methods and properties that can be used for tasks such as adding or removing elements, changing styles, handling events, and more. jQuery is a popular JavaScript library that simplifies DOM manipulation tasks and provides a concise syntax for common operations. However, vanilla JavaScript can also be used effectively for DOM manipulation.