How to change htm h1 from nodejs
To change the h1 tag in an HTML document using Node.js, you can follow these steps:
Import the necessary modules: You need to import the built-in
fs
module, which allows you to read and write files, and thecheerio
module, which provides a jQuery-like syntax to manipulate HTML.Read the HTML file: Use the
fs
module to read the HTML file and store its contents in a variable.Load the HTML into cheerio: Pass the HTML contents to the
cheerio
module'sload()
function to create a jQuery-like object.Modify the h1 tag: Use the
cheerio
object to select the h1 tag and modify its contents.Save the changes: Convert the modified HTML back to a string using the
cheerio
object'shtml()
function and save it to a variable.Write the changes to the HTML file: Use the
fs
module to write the modified HTML string back to the original HTML file.
Here is an example code snippet that demonstrates these steps:
const fs = require('fs');
const cheerio = require('cheerio');
// Step 1: Import necessary modules
// Step 2: Read the HTML file
const html = fs.readFileSync('path/to/html/file.html', 'utf-8');
// Step 3: Load the HTML into cheerio
const $ = cheerio.load(html);
// Step 4: Modify the h1 tag
$('h1').text('New Heading');
// Step 5: Save the changes
const modifiedHtml = $.html();
// Step 6: Write the changes to the HTML file
fs.writeFileSync('path/to/html/file.html', modifiedHtml);
Please note that you need to replace 'path/to/html/file.html'
with the actual path to your HTML file.