- Cheerio provides a library to parse HTML DOM in the server side.
- It provide Jquery($) like DOM manipulation methods.
- You can find more information in the following URL:-
http://cheeriojs.github.io/cheerio/
- In this demo, “We will learn to parse dom string and find element in Node.js code”.
- The cheerio NPM module can be installed using npm install cheerio –save command.The following screenshot shows the terminal with cheerio installation
- To demonstrate the cheerio usage we have created cheer-io-demo project with example1.js and example2.js.The following screenshot shows the structure of cheer-io-demo project.
- The example1 contains the code to parse a single HTML element string and find the text content.The following code shows the content of example1.js file:-
//parsing single element HTML string var cheerio = require('cheerio'), htmlString = "<h1>Welcome Developers</h1>", $ = cheerio.load(htmlString), textContent = $('h1').text(); console.log("textContent: ",textContent);
- The example2 contains code for parsing nested HTML element string and prints the content of a element matched with the supplied selector.The following code shows the content of example2.js file:-
//parsing nested element HTML string var cheerio = require('cheerio'), htmlString = "<div id='divA'><div id='divB'><h1 class='message'>Hello Sandeep</h1>></div></div>", $ = cheerio.load(htmlString), textContent = $('h1.message').text(); console.log("textContent: ",textContent);
- The example1.js can be run using node example1.js command.The following screenshot shows the example1.js in execution.
- The example2.js can be run using node example2.js command.The following screenshot shows the example2.js in execution.
- You can download the demo code from the following link:-
https://github.com/saan1984/cheer-io-demo