To save content as an HTML file using JavaScript, you can utilize the Blob API and the URL.createObjectURL
method. Here’s a complete example:
HTML Code
#html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Save HTML File</title>
</head>
<body>
<textarea id="htmlContent" rows="10" cols="50">
<!DOCTYPE html>
<html>
<head>
<title>Sample HTML</title>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
</textarea>
<br>
<button id="saveButton">Save as HTML</button>
</body>
</html>
#javascript
document.getElementById('saveButton').addEventListener('click', function() {
const content = document.getElementById('htmlContent').value;
const blob = new Blob([content], { type: 'text/html' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'sample.html'; // Desired filename
document.body.appendChild(a);
a.click(); // Trigger the download
document.body.removeChild(a);
URL.revokeObjectURL(url); // Clean up the URL object
});
How It Works:
- Textarea: Users can enter HTML content into the
<textarea>
. - Button: Clicking the “Save as HTML” button triggers the save function.
- Blob Creation: The HTML content from the textarea is converted into a Blob object.
- Download Link: An anchor (
<a>
) element is created with adownload
attribute, which specifies the filename for the saved file. - Simulate Click: The anchor element is clicked programmatically to start the download.
- Cleanup: The URL created for the Blob is revoked to free up memory.
When you run this code, users can input HTML content and save it as sample.html
.
Improving Data Management with Coding Filters!
For developers dealing with large datasets, coding filters provide an effective way to manage data more efficiently. By applying filters to sort, validate, or transform data, developers can ensure that only the necessary data is processed, making applications faster and easier to maintain.