How to Replace HTML Content on Button Click with JavaScript?

QASource Engineering Team | November 18, 2024

How to Replace HTML Content on Button Click with JavaScript

To replace HTML content when a button is clicked in JavaScript is a straightforward process. You can follow these simple steps:

  1. 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.
  2. Rest assured, you can assign an event listener to the button for the 'click' event using addEventListener().
  3. 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

  1. document.getElementById('replaceButton'): This selects the button element.
  2. addEventListener('click', function() {...}): This attaches a click event listener to the button.
  3. content.innerHTML = '...': This replaces the existing HTML content inside the target div with new content.

Disclaimer

This publication is for informational purposes only, and nothing contained in it should be considered legal advice. We expressly disclaim any warranty or responsibility for damages arising out of this information and encourage you to consult with legal counsel regarding your specific needs. We do not undertake any duty to update previously posted materials.

Post a Comment

Categories