In JavaScript, if you want to replace HTML content, you can manipulate the DOM (Document Object Model) using methods like innerHTML, textContent, or various DOM manipulation methods. Below are some examples of how to replace HTML content on a webpage.
Example 1: Using innerHTML
You can replace the entire content of an element using the innerHTML property:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Replace HTML Example</title>
</head>
<body>
<div id="content">
<p>This is the original content.</p>
</div>
<button id="replaceButton">Replace Content</button>
<script>
document.getElementById('replaceButton').addEventListener('click', function() {
document.getElementById('content').innerHTML = '<p>This is the new content!</p>';
});
</script>
</body>
</html>
Example 2: Using textContent
If you want to replace the text without including any HTML, use the textContent property:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Replace Text Example</title>
</head>
<body>
<div id="content">
<p>This is the original content.</p>
</div>
<button id="replaceTextButton">Replace Text</button>
<script>
document.getElementById('replaceTextButton').addEventListener('click', function() {
document.getElementById('content').textContent = 'This is the new text content!';
});
</script>
</body>
</html>
Example 3: Using replaceChild method
You can also replace specific elements using the replaceChild() method:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Replace Child Example</title>
</head>
<body>
<div id="content">
<p id="oldParagraph">This is the old paragraph.</p>
</div>
<button id="replaceChildButton">Replace Child</button>
<script>
document.getElementById('replaceChildButton').addEventListener('click', function() {
const newParagraph = document.createElement('p');
newParagraph.textContent = 'This is the new paragraph!';
const oldParagraph = document.getElementById('oldParagraph');
document.getElementById('content').replaceChild(newParagraph, oldParagraph);
});
</script>
</body>
</html>
Summary
- Use
innerHTML to replace HTML content directly.
- Use
textContent to change the textual content without HTML formatting.
- Use
replaceChild() for more specific manipulations in the DOM.
These methods allow you to dynamically change the content of your web page using JavaScript.