When working with the Cheerio library to process HTML, we can easily remove specific elements such as <div> and <br>. Below, I'll demonstrate how to perform this operation with an example.
First, ensure that Cheerio is installed in your project. If not, you can install it using npm:
bashnpm install cheerio
Next, assume you have an HTML snippet containing <div> and <br> tags. We'll demonstrate how to use Cheerio to remove these elements.
javascriptconst cheerio = require('cheerio'); // Assume this is the HTML we need to process const html = `\n<html>\n<head>\n <title>Test Page</title>\n</head>\n<body>\n <div>Hello, World!</div>\n This is a test.<br>\n <div>Another div</div>\n <p>A paragraph</p>\n</body>\n</html>\n`; // Load the HTML string into Cheerio const $ = cheerio.load(html); // Remove all <div> elements $('div').remove(); // Remove all <br> elements $('br').remove(); // Output the processed HTML console.log($.html());
In this example, we first create a string named html containing our HTML code. Then, we use cheerio.load() to load this HTML, returning an interface similar to jQuery for manipulating the HTML.
Using $('div').remove(); and $('br').remove(); removes all <div> and <br> elements. After this operation, both <div> and <br> tags along with their contents are completely removed from the document.
Finally, we use $.html() to output the processed HTML. You can see that all <div> and <br> tags have been deleted.
This is a basic example of using Cheerio to process and modify HTML documents. You can perform more complex operations as needed.