Fast, flexible, and lean implementation of core jQuery designed specifically for the server.
Teach your server HTML.
var cheerio = require('cheerio'),
$ = cheerio.load('<h2 class="title">Hello world</h2>');
$('h2.title').text('Hello there!');
$('h2').addClass('welcome');
$.html();
//=> <h2 class="title welcome">Hello there!</h2>
npm install cheerio
❤ Familiar syntax: Cheerio implements a subset of core jQuery. Cheerio removes all the DOM inconsistencies and browser cruft from the jQuery library, revealing its truly gorgeous API.
ϟ Blazingly fast: Cheerio works with a very simple, consistent DOM model. As a result parsing, manipulating, and rendering are incredibly efficient. Preliminary end-to-end benchmarks suggest that cheerio is about 8x faster than JSDOM.
❁ Insanely flexible: Cheerio wraps around @FB55's forgiving htmlparser. Cheerio can parse nearly any HTML or XML document.
I wrote cheerio because I found myself increasingly frustrated with JSDOM. For me, there were three main sticking points that I kept running into again and again:
• JSDOM's built-in parser is too strict: JSDOM's bundled HTML parser cannot handle many popular sites out there today.
• JSDOM is too slow: Parsing big websites with JSDOM has a noticeable delay.
• JSDOM feels too heavy: The goal of JSDOM is to provide an identical DOM environment as what we see in the browser. I never really needed all this, I just wanted a simple, familiar way to do HTML manipulation.
Cheerio will not solve all your problems. I would still use JSDOM if I needed to work in a browser-like environment on the server, particularly if I wanted to automate functional tests.
<ul id="fruits">
<li class="apple">Apple</li>
<li class="orange">Orange</li>
<li class="pear">Pear</li>
</ul>
This is the HTML markup we will be using in all of the API examples.
First you need to load in the HTML. This step in jQuery is implicit, since jQuery operates on the one, baked-in DOM. With Cheerio, we need to pass in the HTML document.
This is the preferred method:
var cheerio = require('cheerio'),
$ = cheerio.load('<ul id="fruits">...</ul>');
Optionally, you can also load in the HTML by passing the string as the context:
$ = require('cheerio');
$('ul', '<ul id="fruits">...</ul>');
Or as the root:
$ = require('cheerio');
$('li', 'ul', '<ul id="fruits">...</ul>');
You can also pass an extra object to .load()
if you need to modify any
of the default parsing options:
$ = cheerio.load('<ul id="fruits">...</ul>', {
ignoreWhitespace: true,
xmlMode: true
});
These parsing options are taken directly from htmlparser, therefore any options that can be used in htmlparser are valid in cheerio as well. The default options are:
{
ignoreWhitespace: false,
xmlMode: false,
lowerCaseTags: false
}
For a list of options and their effects, see this and this.
Cheerio's selector implementation is nearly identical to jQuery's, so the API is very similar.
selector
searches within the context
scope which searches within the root
scope. selector
and context
can be an string expression, DOM Element, array of DOM elements, or cheerio object. root
is typically the HTML document string.
This selector method is the starting point for traversing and manipulating the document. Like jQuery, it's the primary method for selecting elements in the document, but unlike jQuery it's built on top of the CSSSelect library, which implements most of the Sizzle selectors.
$('.apple', '#fruits').text()
//=> Apple
$('ul .pear').attr('class')
//=> pear
$('li[class=orange]').html()
//=> <li class="orange">Orange</li>
Methods for getting and modifying attributes.
Method for getting and setting attributes. Gets the attribute value for only the first element in the matched set. If you set an attribute's value to null
, you remove that attribute. You may also pass a map
and function
like jQuery.
$('ul').attr('id')
//=> fruits
$('.apple').attr('id', 'favorite').html()
//=> <li class="apple" id="favorite">Apple</li>
See http://api.jquery.com/attr/ for more information
Method for getting and setting the value of input, select, and textarea. Note: Support for map
, and function
has not been added yet.
$('input[type="text"]').val()
=> input_text
$('input[type="text"]').val('test').html()
=> <input type="text" value="test"/>
Method for removing attributes by name
.
$('.pear').removeAttr('class').html()
//=> <li>Pear</li>
Check to see if any of the matched elements have the given className
.
$('.pear').hasClass('pear')
//=> true
$('apple').hasClass('fruit')
//=> false
$('li').hasClass('pear')
//=> true
Adds class(es) to all of the matched elements. Also accepts a function
like jQuery.
$('.pear').addClass('fruit').html()
//=> <li class="pear fruit">Pear</li>
$('.apple').addClass('fruit red').html()
//=> <li class="apple fruit red">Apple</li>
See http://api.jquery.com/addClass/ for more information.
Removes one or more space-separated classes from the selected elements. If no className
is defined, all classes will be removed. Also accepts a function
like jQuery.
$('.pear').removeClass('pear').html()
//=> <li class="">Pear</li>
$('.apple').addClass('red').removeClass().html()
//=> <li class="">Apple</li>
See http://api.jquery.com/removeClass/ for more information.
Modify the current collection by adding the results of performing the CSS selector on the whole document, or, if context is given, just inside context elements.
Get a set of descendants filtered by selector
of each element in the current set of matched elements.
$('#fruits').find('li').length
//=> 3
Traverse upwards from the current element to find the first element that matches the selector. If context node is given, consider only elements that are its descendants. This method is similar to parents(selector), but it only returns the first ancestor matched.
Gets the parent of the first selected element.
$('.pear').parent().attr('id')
//=> fruits
Get a set of parents filtered by selector
of each element in the current set of match elements.
$('.orange').parents().length
// => 2
$('.orange').parents('#fruits').length
// => 1
Get the closest element that matches the selector by searching through the element and the elements parents.
$('.orange').closest()
// => []
$('.orange').closest('.apple')
// => []
$('.orange').closest('li')
// => [<li class="orange">Orange</li>]
$('.orange').closest('#fruits')
// => [<ul id="fruits"> ... </ul>]
Gets the next sibling of the first selected element.
$('.apple').next().hasClass('orange')
//=> true
Gets the previous sibling of the first selected element.
$('.orange').prev().hasClass('apple')
//=> true
Gets the elements matching the specified range
$('li').slice(1).eq(0).text()
//=> 'Orange'
$('li').slice(1, 2).length
//=> 1
Gets the first selected element's siblings, excluding itself.
$('.pear').siblings().length
//=> 2
$('.pear').siblings('.orange').length
//=> 1
Gets the children of the first selected element.
$('#fruits').children().length
//=> 3
$('#fruits').children('.pear').text()
//=> Pear
Iterates over a cheerio object, executing a function for each matched element. When the callback is fired, the function is fired in the context of the DOM element, so this
refers to the current element, which is equivalent to the function parameter element
. To break out of the each
loop early, return with false
.
var fruits = [];
$('li').each(function(i, elem) {
fruits[i] = $(this).text();
});
fruits.join(', ');
//=> Apple, Orange, Pear
Iterates over a cheerio object, executing a function for each selected element. Map will return an array
of return values from each of the functions it iterated over. The function is fired in the context of the DOM element, so this
refers to the current element, which is equivalent to the function parameter element
.
$('li').map(function(i, el) {
// this === el
return $(this).attr('class');
}).join(', ');
//=> apple, orange, pear
Iterates over a cheerio object, reducing the set of selector elements to those that match the selector or pass the function's test. If using the function method, the function is executed in the context of the selected element, so this
refers to the current element.
Selector:
$('li').filter('.orange').attr('class');
//=> orange
Function:
$('li').filter(function(i, el) {
// this === el
return $(this).attr('class') === 'orange';
}).attr('class')
//=> orange
Will select the first element of a cheerio object
$('#fruits').children().first().text()
//=> Apple
Will select the last element of a cheerio object
$('#fruits').children().last().text()
//=> Pear
Reduce the set of matched elements to the one at the specified index. Use .eq(-i)
to count backwards from the last selected element.
$('li').eq(0).text()
//=> Apple
$('li').eq(-1).text()
//=> Pear
Iterate through every element of the collection. Similar to each, but the arguments for the iterator functions are different, and returning false from the iterator won’t stop the iteration.
Wrap an HTML structure around the content of each element in the set of matched elements.
Wrap an HTML structure around all elements in the set of matched elements.
Wrap an HTML structure around each element in the set of matched elements.
Remove immediate parent nodes of each element in the collection and put their children in their place. Basically, this method removes one level of ancestry while keeping current elements in the DOM.
Add elements to the end of the current collection.
Modify the collection by adding elements to it. If any of the arguments is an array, its elements are merged into the current collection.
Identical to Array.reduce that iterates over current collection.
Check if the first element of the current collection matches the CSS selector. For basic support of jQuery’s non-standard pseudo-selectors such as :visible, include the optional “selector” module.
Methods for modifying the DOM structure.
Inserts content as the last child of each of the selected elements.
$('ul').append('<li class="plum">Plum</li>')
$.html()
//=> <ul id="fruits">
// <li class="apple">Apple</li>
// <li class="orange">Orange</li>
// <li class="pear">Pear</li>
// <li class="plum">Plum</li>
// </ul>
Inserts content as the first child of each of the selected elements.
$('ul').prepend('<li class="plum">Plum</li>')
$.html()
//=> <ul id="fruits">
// <li class="plum">Plum</li>
// <li class="apple">Apple</li>
// <li class="orange">Orange</li>
// <li class="pear">Pear</li>
// </ul>
Append elements from the current collection to the target element. This is like append, but with reversed operands.
Prepend elements of the current collection inside each of the target elements. This is like prepend, only with reversed operands.
Insert content next to each element in the set of matched elements.
$('.apple').after('<li class="plum">Plum</li>')
$.html()
//=> <ul id="fruits">
// <li class="apple">Apple</li>
// <li class="plum">Plum</li>
// <li class="orange">Orange</li>
// <li class="pear">Pear</li>
// </ul>
Insert content previous to each element in the set of matched elements.
$('.apple').before('<li class="plum">Plum</li>')
$.html()
//=> <ul id="fruits">
// <li class="plum">Plum</li>
// <li class="apple">Apple</li>
// <li class="orange">Orange</li>
// <li class="pear">Pear</li>
// </ul>
Removes the set of matched elements from the DOM and all their children. selector
filters the set of matched elements to be removed.
$('.pear').remove()
$.html()
//=> <ul id="fruits">
// <li class="apple">Apple</li>
// <li class="orange">Orange</li>
// </ul>
Replaces matched elements with content
.
var plum = $('<li class="plum">Plum</li>')
$('.pear').replaceWith(plum)
$.html()
//=> <ul id="fruits">
// <li class="apple">Apple</li>
// <li class="orange">Orange</li>
// <li class="plum">Plum</li>
// </ul>
Empties an element, removing all it's children.
$('ul').empty()
$.html()
//=> <ul id="fruits"></ul>
Gets an html content string from the first selected element. If htmlString
is specified, each selected element's content is replaced by the new content.
$('.orange').html()
//=> Orange
$('#fruits').html('<li class="mango">Mango</li>').html()
//=> <li class="mango">Mango</li>
Get the combined text contents of each element in the set of matched elements, including their descendants.. If textString
is specified, each selected element's content is replaced by the new text content.
$('.orange').text()
//=> Orange
$('ul').text()
//=> Apple
// Orange
// Pear
Get or set the value of form controls. When no value is given, return the value of the first element. For , an array of values is returend. When a value is given, set all elements to this value.