Cheerio is a fast, flexible, and high-performance Node.js library primarily used for server-side emulation of jQuery's core functionality to parse and manipulate HTML. This is particularly useful for web crawlers or server-side page analysis.
In Cheerio, the get() function is primarily used to retrieve native HTML elements from Cheerio objects (typically generated by queries similar to jQuery selectors). Using get() allows direct access to DOM elements rather than through Cheerio's wrapper objects.
Usage Examples
Assume we have the following HTML code:
html<ul id="fruits"> <li class="apple">Apple</li> <li class="orange">Orange</li> <li class="pear">Pear</li> </ul>
If we want to retrieve the native list of all <li> tags in this HTML, we can use Cheerio to load this HTML and then use selectors with the get() function:
javascriptconst cheerio = require('cheerio'); const html = '<ul id="fruits"><li class="apple">Apple</li><li class="orange">Orange</li><li class="pear">Pear</li></ul>'; const $ = cheerio.load(html); const liElements = $('li').get(); liElements.forEach(element => { console.log(element.tagName); // Output: li });
In this example, $('li') selects all <li> tags and returns a Cheerio collection object. Calling .get() converts this collection into an array containing native HTML elements. Then, we can iterate over this array and directly access properties of each element, such as tagName.
Summary
The get() function in the Cheerio library is a very practical tool, especially when you need to directly handle native DOM elements. It streamlines the conversion from Cheerio objects to native DOM, making operations more direct and flexible.