
To replace HTML content when a button is clicked in JavaScript is a straightforward process. You can follow these simple steps:
- To select the HTML element you want to change, choose the method that best suits your needs. You can use document.getElementById(), document.querySelector(), or other DOM selection methods.
- Rest assured, you can assign an event listener to the button for the 'click' event using addEventListener().
- Depending on the type of content you want to update, you can modify the inner HTML of the target element using the innerHTML property or textContent.
Example with code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Replace Content Example</title>
</head>
<body>
<div id="content">This is the original content.</div>
<button id="replaceButton">Click me</button>
<script>
// Select the button and content element
const button = document.getElementById('replaceButton');
const content = document.getElementById('content');
// Add event listener to the button
button.addEventListener('click', function() {
// Replace the HTML content inside the div
content.innerHTML = 'The content has been replaced!';
});
</script>
</body>
</html>
Summary
- document.getElementById('replaceButton'): This selects the button element.
- addEventListener('click', function() {...}): This attaches a click event listener to the button.
- content.innerHTML = '...': This replaces the existing HTML content inside the target div with new content.
Post a Comment