You can add or remove HTML content inside a div using JavaScript by accessing the innerHTML
property of the div element. Here’s how you can do it:
1. Adding HTML content
To add HTML content inside a div, you simply set the innerHTML
property of the div to the HTML content you want to add:
// Get the reference to the div element
var myDiv = document.getElementById("myDiv");
// HTML content to be added
var htmlContent = "<p>This is the added HTML content.</p>";
// Set the innerHTML property of the div
myDiv.innerHTML = htmlContent;
This will replace any existing content inside the div with the new HTML content.
2. Removing HTML content
To remove HTML content from a div, you can set the innerHTML
property to an empty string (''
):
// Get the reference to the div element
var myDiv = document.getElementById("myDiv");
// Remove all HTML content inside the div
myDiv.innerHTML = "";
This will effectively remove all content inside the div.
Here’s an example HTML structure with a div element:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Adding and Removing HTML Content</title>
</head>
<body>
<div id="myDiv">
<!-- Content will be added or removed here -->
</div>
<script>
// JavaScript code for adding or removing HTML content
</script>
</body>
</html>
Replace 'myDiv'
with the actual ID of your div element. Then, use the JavaScript code snippets provided above to add or remove HTML content as needed.