Software Development and QA Tips By QASource Experts

Replace HTML Content on Button Click with JavaScript

Written by QASource Engineering Team | Nov 18, 2024 5:00:00 PM

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.