34 | ```
35 |
36 | ## Note
37 |
38 | We are currently working on the 1.0.0 release of cheerio on the `master` branch. The source code for the last published version, `0.22.0`, can be found [here](https://github.com/cheeriojs/cheerio/tree/aa90399c9c02f12432bfff97b8f1c7d8ece7c307).
39 |
40 | ## Installation
41 | `npm install cheerio`
42 |
43 | ## Features
44 | __❤ Familiar syntax:__
45 | 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.
46 |
47 | __ϟ Blazingly fast:__
48 | 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.
49 |
50 | __❁ Incredibly flexible:__
51 | Cheerio wraps around @FB55's forgiving [htmlparser2](https://github.com/fb55/htmlparser2/). Cheerio can parse nearly any HTML or XML document.
52 |
53 | ## Cheerio is not a web browser
54 |
55 | Cheerio parses markup and provides an API for traversing/manipulating the resulting data structure. It does not interpret the result as a web browser does. Specifically, it does *not* produce a visual rendering, apply CSS, load external resources, or execute JavaScript. If your use case requires any of this functionality, you should consider projects like [PhantomJS](http://phantomjs.org/) or [JSDom](https://github.com/tmpvar/jsdom).
56 |
57 | ## API
58 |
59 | ### Table of contents
60 |
61 |
62 | Selectors
63 |
64 | - [$( selector, [context], [root] )](#-selector-context-root-)
65 |
66 |
67 | Attributes
68 |
69 | - [.attr( name, value )](#attr-name-value-)
70 | - [.prop( name, value )](#prop-name-value-)
71 | - [.data( name, value )](#data-name-value-)
72 | - [.val( [value] )](#val-value-)
73 | - [.removeAttr( name )](#removeattr-name-)
74 | - [.hasClass( className )](#hasclass-classname-)
75 | - [.addClass( className )](#addclass-classname-)
76 | - [.removeClass( [className] )](#removeclass-classname-)
77 | - [.toggleClass( className, [switch] )](#toggleclass-classname-switch-)
78 | - [.is( selector )](#is-selector-)
79 | - [.is( element )](#is-element-)
80 | - [.is( selection )](#is-selection-)
81 | - [.is( function(index) )](#is-functionindex-)
82 |
83 |
84 | Forms
85 |
86 | - [.serialize()](#serialize)
87 | - [.serializeArray()](#serializearray)
88 |
89 |
90 | Traversing
91 |
92 | - [.find(selector)](#findselector)
93 | - [.find(selection)](#findselection)
94 | - [.find(node)](#findnode)
95 | - [.parent([selector])](#parentselector)
96 | - [.parents([selector])](#parentsselector)
97 | - [.parentsUntil([selector][,filter])](#parentsuntilselectorfilter)
98 | - [.closest(selector)](#closestselector)
99 | - [.next([selector])](#nextselector)
100 | - [.nextAll([selector])](#nextallselector)
101 | - [.nextUntil([selector], [filter])](#nextuntilselector-filter)
102 | - [.prev([selector])](#prevselector)
103 | - [.prevAll([selector])](#prevallselector)
104 | - [.prevUntil([selector], [filter])](#prevuntilselector-filter)
105 | - [.slice( start, [end] )](#slice-start-end-)
106 | - [.siblings([selector])](#siblingsselector)
107 | - [.children([selector])](#childrenselector)
108 | - [.contents()](#contents)
109 | - [.each( function(index, element) )](#each-functionindex-element-)
110 | - [.map( function(index, element) )](#map-functionindex-element-)
111 | - [.filter( selector )
112 | .filter( selection )
113 | .filter( element )
114 | .filter( function(index, element) )](#filter-selector---filter-selection---filter-element---filter-functionindex-element-)
115 | - [.not( selector )
116 | .not( selection )
117 | .not( element )
118 | .not( function(index, elem) )](#not-selector---not-selection---not-element---not-functionindex-elem-)
119 | - [.has( selector )
120 | .has( element )](#has-selector---has-element-)
121 | - [.first()](#first)
122 | - [.last()](#last)
123 | - [.eq( i )](#eq-i-)
124 | - [.get( [i] )](#get-i-)
125 | - [.index()](#index)
126 | - [.index( selector )](#index-selector-)
127 | - [.index( nodeOrSelection )](#index-nodeorselection-)
128 | - [.end()](#end)
129 | - [.add( selector [, context] )](#add-selector--context-)
130 | - [.add( element )](#add-element-)
131 | - [.add( elements )](#add-elements-)
132 | - [.add( html )](#add-html-)
133 | - [.add( selection )](#add-selection-)
134 | - [.addBack( [filter] )](#addback-filter-)
135 |
136 |
137 | Manipulation
138 |
139 | - [.append( content, [content, ...] )](#append-content-content--)
140 | - [.appendTo( target )](#appendto-target-)
141 | - [.prepend( content, [content, ...] )](#prepend-content-content--)
142 | - [.prependTo( target )](#prependto-target-)
143 | - [.after( content, [content, ...] )](#after-content-content--)
144 | - [.insertAfter( target )](#insertafter-target-)
145 | - [.before( content, [content, ...] )](#before-content-content--)
146 | - [.insertBefore( target )](#insertbefore-target-)
147 | - [.remove( [selector] )](#remove-selector-)
148 | - [.replaceWith( content )](#replacewith-content-)
149 | - [.empty()](#empty)
150 | - [.html( [htmlString] )](#html-htmlstring-)
151 | - [.text( [textString] )](#text-textstring-)
152 | - [.wrap( content )](#wrap-content-)
153 | - [.css( [propertName] )
154 | .css( [ propertyNames] )
155 | .css( [propertyName], [value] )
156 | .css( [propertName], [function] )
157 | .css( [properties] )](#css-propertname---css--propertynames---css-propertyname-value---css-propertname-function---css-properties-)
158 |
159 |
160 | ### Markup example we'll be using:
161 |
162 | ```html
163 |
164 |
Apple
165 |
Orange
166 |
Pear
167 |
168 | ```
169 |
170 | This is the HTML markup we will be using in all of the API examples.
171 |
172 | ### Loading
173 | 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.
174 |
175 | This is the _preferred_ method:
176 |
177 | ```js
178 | const cheerio = require('cheerio');
179 | const $ = cheerio.load('
...
');
180 | ```
181 |
182 | Optionally, you can also load in the HTML by passing the string as the context:
183 |
184 | ```js
185 | const $ = require('cheerio');
186 | $('ul', '
...
');
187 | ```
188 |
189 | Or as the root:
190 |
191 | ```js
192 | const $ = require('cheerio');
193 | $('li', 'ul', '
...
');
194 | ```
195 |
196 | You can also pass an extra object to `.load()` if you need to modify any
197 | of the default parsing options:
198 |
199 | ```js
200 | const $ = cheerio.load('
...
', {
201 | normalizeWhitespace: true,
202 | xmlMode: true
203 | });
204 | ```
205 |
206 | These parsing options are taken directly from [htmlparser2](https://github.com/fb55/htmlparser2/wiki/Parser-options), therefore any options that can be used in `htmlparser2` are valid in cheerio as well. The default options are:
207 |
208 | ```js
209 | {
210 | withDomLvl1: true,
211 | normalizeWhitespace: false,
212 | xmlMode: false,
213 | decodeEntities: true
214 | }
215 |
216 | ```
217 |
218 | For a full list of options and their effects, see [this](https://github.com/fb55/DomHandler) and
219 | [htmlparser2's options](https://github.com/fb55/htmlparser2/wiki/Parser-options).
220 |
221 | ### Selectors
222 |
223 | Cheerio's selector implementation is nearly identical to jQuery's, so the API is very similar.
224 |
225 | #### $( selector, [context], [root] )
226 | `selector` searches within the `context` scope which searches within the `root` scope. `selector` and `context` can be a string expression, DOM Element, array of DOM elements, or cheerio object. `root` is typically the HTML document string.
227 |
228 | 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.
229 |
230 | ```js
231 | $('.apple', '#fruits').text()
232 | //=> Apple
233 |
234 | $('ul .pear').attr('class')
235 | //=> pear
236 |
237 | $('li[class=orange]').html()
238 | //=> Orange
239 | ```
240 |
241 | ##### XML Namespaces
242 | You can select with XML Namespaces but [due to the CSS specification](https://www.w3.org/TR/2011/REC-css3-selectors-20110929/#attribute-selectors), the colon (`:`) needs to be escaped for the selector to be valid.
243 |
244 | ```js
245 | $('[xml\\:id="main"');
246 | ```
247 |
248 | ### Attributes
249 | Methods for getting and modifying attributes.
250 |
251 | #### .attr( name, value )
252 | 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.
253 |
254 | ```js
255 | $('ul').attr('id')
256 | //=> fruits
257 |
258 | $('.apple').attr('id', 'favorite').html()
259 | //=>
Apple
260 | ```
261 |
262 | > See http://api.jquery.com/attr/ for more information
263 |
264 | #### .prop( name, value )
265 | Method for getting and setting properties. Gets the property value for only the first element in the matched set.
266 |
267 | ```js
268 | $('input[type="checkbox"]').prop('checked')
269 | //=> false
270 |
271 | $('input[type="checkbox"]').prop('checked', true).val()
272 | //=> ok
273 | ```
274 |
275 | > See http://api.jquery.com/prop/ for more information
276 |
277 | #### .data( name, value )
278 | Method for getting and setting data attributes. Gets or sets the data attribute value for only the first element in the matched set.
279 |
280 | ```js
281 | $('').data()
282 | //=> { appleColor: 'red' }
283 |
284 | $('').data('apple-color')
285 | //=> 'red'
286 |
287 | const apple = $('.apple').data('kind', 'mac')
288 | apple.data('kind')
289 | //=> 'mac'
290 | ```
291 |
292 | > See http://api.jquery.com/data/ for more information
293 |
294 | #### .val( [value] )
295 | Method for getting and setting the value of input, select, and textarea. Note: Support for `map`, and `function` has not been added yet.
296 |
297 | ```js
298 | $('input[type="text"]').val()
299 | //=> input_text
300 |
301 | $('input[type="text"]').val('test').html()
302 | //=>
303 | ```
304 |
305 | #### .removeAttr( name )
306 | Method for removing attributes by `name`.
307 |
308 | ```js
309 | $('.pear').removeAttr('class').html()
310 | //=>
Pear
311 | ```
312 |
313 | #### .hasClass( className )
314 | Check to see if *any* of the matched elements have the given `className`.
315 |
316 | ```js
317 | $('.pear').hasClass('pear')
318 | //=> true
319 |
320 | $('apple').hasClass('fruit')
321 | //=> false
322 |
323 | $('li').hasClass('pear')
324 | //=> true
325 | ```
326 |
327 | #### .addClass( className )
328 | Adds class(es) to all of the matched elements. Also accepts a `function` like jQuery.
329 |
330 | ```js
331 | $('.pear').addClass('fruit').html()
332 | //=>
336 | ```
337 |
338 | > See http://api.jquery.com/addClass/ for more information.
339 |
340 | #### .removeClass( [className] )
341 | 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.
342 |
343 | ```js
344 | $('.pear').removeClass('pear').html()
345 | //=>
349 | ```
350 |
351 | > See http://api.jquery.com/removeClass/ for more information.
352 |
353 | #### .toggleClass( className, [switch] )
354 | Add or remove class(es) from the matched elements, depending on either the class's presence or the value of the switch argument. Also accepts a `function` like jQuery.
355 |
356 | ```js
357 | $('.apple.green').toggleClass('fruit green red').html()
358 | //=>
362 | ```
363 |
364 | > See http://api.jquery.com/toggleClass/ for more information.
365 |
366 | #### .is( selector )
367 | #### .is( element )
368 | #### .is( selection )
369 | #### .is( function(index) )
370 | Checks the current list of elements and returns `true` if _any_ of the elements match the selector. If using an element or Cheerio selection, returns `true` if _any_ of the elements match. If using a predicate function, the function is executed in the context of the selected element, so `this` refers to the current element.
371 |
372 | ### Forms
373 |
374 | #### .serialize()
375 |
376 | Encodes a set of form elements as a URL query string.
377 |
378 | ```js
379 | $('').serialize()
380 | //=> foo=bar&foo=qux
381 | ```
382 |
383 | #### .serializeArray()
384 |
385 | Encode a set of form elements as an array of names and values.
386 |
387 | ```js
388 | $('').serializeArray()
389 | //=> [ { name: 'foo', value: 'bar' } ]
390 | ```
391 |
392 | ### Traversing
393 |
394 | #### .find(selector)
395 | #### .find(selection)
396 | #### .find(node)
397 | Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
398 |
399 | ```js
400 | $('#fruits').find('li').length
401 | //=> 3
402 | $('#fruits').find($('.apple')).length
403 | //=> 1
404 | ```
405 |
406 | #### .parent([selector])
407 | Get the parent of each element in the current set of matched elements, optionally filtered by a selector.
408 |
409 | ```js
410 | $('.pear').parent().attr('id')
411 | //=> fruits
412 | ```
413 |
414 | #### .parents([selector])
415 | Get a set of parents filtered by `selector` of each element in the current set of match elements.
416 | ```js
417 | $('.orange').parents().length
418 | // => 2
419 | $('.orange').parents('#fruits').length
420 | // => 1
421 | ```
422 |
423 | #### .parentsUntil([selector][,filter])
424 | Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or cheerio object.
425 | ```js
426 | $('.orange').parentsUntil('#food').length
427 | // => 1
428 | ```
429 |
430 | #### .closest(selector)
431 | For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
432 |
433 | ```js
434 | $('.orange').closest()
435 | // => []
436 | $('.orange').closest('.apple')
437 | // => []
438 | $('.orange').closest('li')
439 | // => [
]
460 | ```
461 |
462 | #### .nextUntil([selector], [filter])
463 | Gets all the following siblings up to but not including the element matched by the selector, optionally filtered by another selector.
464 |
465 | ```js
466 | $('.apple').nextUntil('.pear')
467 | //=> [
Orange
]
468 | ```
469 |
470 | #### .prev([selector])
471 | Gets the previous sibling of the first selected element optionally filtered by a selector.
472 |
473 | ```js
474 | $('.orange').prev().hasClass('apple')
475 | //=> true
476 | ```
477 |
478 | #### .prevAll([selector])
479 | Gets all the preceding siblings of the first selected element, optionally filtered by a selector.
480 |
481 | ```js
482 | $('.pear').prevAll()
483 | //=> [
]
486 | ```
487 |
488 | #### .prevUntil([selector], [filter])
489 | Gets all the preceding siblings up to but not including the element matched by the selector, optionally filtered by another selector.
490 |
491 | ```js
492 | $('.pear').prevUntil('.apple')
493 | //=> [
Orange
]
494 | ```
495 |
496 | #### .slice( start, [end] )
497 | Gets the elements matching the specified range
498 |
499 | ```js
500 | $('li').slice(1).eq(0).text()
501 | //=> 'Orange'
502 |
503 | $('li').slice(1, 2).length
504 | //=> 1
505 | ```
506 |
507 | #### .siblings([selector])
508 | Gets the first selected element's siblings, excluding itself.
509 |
510 | ```js
511 | $('.pear').siblings().length
512 | //=> 2
513 |
514 | $('.pear').siblings('.orange').length
515 | //=> 1
516 |
517 | ```
518 |
519 | #### .children([selector])
520 | Gets the children of the first selected element.
521 |
522 | ```js
523 | $('#fruits').children().length
524 | //=> 3
525 |
526 | $('#fruits').children('.pear').text()
527 | //=> Pear
528 | ```
529 |
530 | #### .contents()
531 | Gets the children of each element in the set of matched elements, including text and comment nodes.
532 |
533 | ```js
534 | $('#fruits').contents().length
535 | //=> 3
536 | ```
537 |
538 | #### .each( function(index, element) )
539 | 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`.
540 |
541 | ```js
542 | const fruits = [];
543 |
544 | $('li').each(function(i, elem) {
545 | fruits[i] = $(this).text();
546 | });
547 |
548 | fruits.join(', ');
549 | //=> Apple, Orange, Pear
550 | ```
551 |
552 | #### .map( function(index, element) )
553 | Pass each element in the current matched set through a function, producing a new Cheerio object containing the return values. The function can return an individual data item or an array of data items to be inserted into the resulting set. If an array is returned, the elements inside the array are inserted into the set. If the function returns null or undefined, no element will be inserted.
554 |
555 | ```js
556 | $('li').map(function(i, el) {
557 | // this === el
558 | return $(this).text();
559 | }).get().join(' ');
560 | //=> "apple orange pear"
561 | ```
562 |
563 | #### .filter( selector ) .filter( selection ) .filter( element ) .filter( function(index, element) )
564 |
565 | Iterates over a cheerio object, reducing the set of selector elements to those that match the selector or pass the function's test. When a Cheerio selection is specified, return only the elements contained in that selection. When an element is specified, return only that element (if it is contained in the original selection). If using the function method, the function is executed in the context of the selected element, so `this` refers to the current element.
566 |
567 | Selector:
568 |
569 | ```js
570 | $('li').filter('.orange').attr('class');
571 | //=> orange
572 | ```
573 |
574 | Function:
575 |
576 | ```js
577 | $('li').filter(function(i, el) {
578 | // this === el
579 | return $(this).attr('class') === 'orange';
580 | }).attr('class')
581 | //=> orange
582 | ```
583 |
584 | #### .not( selector ) .not( selection ) .not( element ) .not( function(index, elem) )
585 |
586 | Remove elements from the set of matched elements. Given a jQuery object that represents a set of DOM elements, the `.not()` method constructs a new jQuery object from a subset of the matching elements. The supplied selector is tested against each element; the elements that don't match the selector will be included in the result. The `.not()` method can take a function as its argument in the same way that `.filter()` does. Elements for which the function returns true are excluded from the filtered set; all other elements are included.
587 |
588 | Selector:
589 |
590 | ```js
591 | $('li').not('.apple').length;
592 | //=> 2
593 | ```
594 |
595 | Function:
596 |
597 | ```js
598 | $('li').not(function(i, el) {
599 | // this === el
600 | return $(this).attr('class') === 'orange';
601 | }).length;
602 | //=> 2
603 | ```
604 |
605 | #### .has( selector ) .has( element )
606 |
607 | Filters the set of matched elements to only those which have the given DOM element as a descendant or which have a descendant that matches the given selector. Equivalent to `.filter(':has(selector)')`.
608 |
609 | Selector:
610 |
611 | ```js
612 | $('ul').has('.pear').attr('id');
613 | //=> fruits
614 | ```
615 |
616 | Element:
617 |
618 | ```js
619 | $('ul').has($('.pear')[0]).attr('id');
620 | //=> fruits
621 | ```
622 |
623 | #### .first()
624 | Will select the first element of a cheerio object
625 |
626 | ```js
627 | $('#fruits').children().first().text()
628 | //=> Apple
629 | ```
630 |
631 | #### .last()
632 | Will select the last element of a cheerio object
633 |
634 | ```js
635 | $('#fruits').children().last().text()
636 | //=> Pear
637 | ```
638 |
639 | #### .eq( i )
640 | Reduce the set of matched elements to the one at the specified index. Use `.eq(-i)` to count backwards from the last selected element.
641 |
642 | ```js
643 | $('li').eq(0).text()
644 | //=> Apple
645 |
646 | $('li').eq(-1).text()
647 | //=> Pear
648 | ```
649 |
650 | #### .get( [i] )
651 |
652 | Retrieve the DOM elements matched by the Cheerio object. If an index is specified, retrieve one of the elements matched by the Cheerio object:
653 |
654 | ```js
655 | $('li').get(0).tagName
656 | //=> li
657 | ```
658 |
659 | If no index is specified, retrieve all elements matched by the Cheerio object:
660 |
661 | ```js
662 | $('li').get().length
663 | //=> 3
664 | ```
665 |
666 | #### .index()
667 | #### .index( selector )
668 | #### .index( nodeOrSelection )
669 |
670 | Search for a given element from among the matched elements.
671 |
672 | ```js
673 | $('.pear').index()
674 | //=> 2
675 | $('.orange').index('li')
676 | //=> 1
677 | $('.apple').index($('#fruit, li'))
678 | //=> 1
679 | ```
680 |
681 | #### .end()
682 | End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.
683 |
684 | ```js
685 | $('li').eq(0).end().length
686 | //=> 3
687 | ```
688 |
689 | #### .add( selector [, context] )
690 | #### .add( element )
691 | #### .add( elements )
692 | #### .add( html )
693 | #### .add( selection )
694 | Add elements to the set of matched elements.
695 |
696 | ```js
697 | $('.apple').add('.orange').length
698 | //=> 2
699 | ```
700 |
701 | #### .addBack( [filter] )
702 |
703 | Add the previous set of elements on the stack to the current set, optionally filtered by a selector.
704 |
705 | ```js
706 | $('li').eq(0).addBack('.orange').length
707 | //=> 2
708 | ```
709 |
710 | ### Manipulation
711 | Methods for modifying the DOM structure.
712 |
713 | #### .append( content, [content, ...] )
714 | Inserts content as the *last* child of each of the selected elements.
715 |
716 | ```js
717 | $('ul').append('
Plum
')
718 | $.html()
719 | //=>
720 | //
Apple
721 | //
Orange
722 | //
Pear
723 | //
Plum
724 | //
725 | ```
726 |
727 | #### .appendTo( target )
728 | Insert every element in the set of matched elements to the end of the target.
729 |
730 | ```js
731 | $('
Plum
').appendTo('#fruits')
732 | $.html()
733 | //=>
734 | //
Apple
735 | //
Orange
736 | //
Pear
737 | //
Plum
738 | //
739 | ```
740 |
741 | #### .prepend( content, [content, ...] )
742 | Inserts content as the *first* child of each of the selected elements.
743 |
744 | ```js
745 | $('ul').prepend('
Plum
')
746 | $.html()
747 | //=>
748 | //
Plum
749 | //
Apple
750 | //
Orange
751 | //
Pear
752 | //
753 | ```
754 |
755 | #### .prependTo( target )
756 | Insert every element in the set of matched elements to the beginning of the target.
757 |
758 | ```js
759 | $('
Plum
').prependTo('#fruits')
760 | $.html()
761 | //=>
762 | //
Plum
763 | //
Apple
764 | //
Orange
765 | //
Pear
766 | //
767 | ```
768 |
769 | #### .after( content, [content, ...] )
770 | Insert content next to each element in the set of matched elements.
771 |
772 | ```js
773 | $('.apple').after('
Plum
')
774 | $.html()
775 | //=>
776 | //
Apple
777 | //
Plum
778 | //
Orange
779 | //
Pear
780 | //
781 | ```
782 |
783 | #### .insertAfter( target )
784 | Insert every element in the set of matched elements after the target.
785 |
786 | ```js
787 | $('
795 | ```
796 |
797 | #### .before( content, [content, ...] )
798 | Insert content previous to each element in the set of matched elements.
799 |
800 | ```js
801 | $('.apple').before('
Plum
')
802 | $.html()
803 | //=>
804 | //
Plum
805 | //
Apple
806 | //
Orange
807 | //
Pear
808 | //
809 | ```
810 |
811 | #### .insertBefore( target )
812 | Insert every element in the set of matched elements before the target.
813 |
814 | ```js
815 | $('
823 | ```
824 |
825 | #### .remove( [selector] )
826 | Removes the set of matched elements from the DOM and all their children. `selector` filters the set of matched elements to be removed.
827 |
828 | ```js
829 | $('.pear').remove()
830 | $.html()
831 | //=>
858 | ```
859 |
860 | #### .html( [htmlString] )
861 | 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.
862 |
863 | ```js
864 | $('.orange').html()
865 | //=> Orange
866 |
867 | $('#fruits').html('
Mango
').html()
868 | //=>
Mango
869 | ```
870 |
871 | #### .text( [textString] )
872 | 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.
873 |
874 | ```js
875 | $('.orange').text()
876 | //=> Orange
877 |
878 | $('ul').text()
879 | //=> Apple
880 | // Orange
881 | // Pear
882 | ```
883 |
884 | #### .wrap( content )
885 | The .wrap() function can take any string or object that could be passed to the $() factory function to specify a DOM structure. This structure may be nested several levels deep, but should contain only one inmost element. A copy of this structure will be wrapped around each of the elements in the set of matched elements. This method returns the original set of elements for chaining purposes.
886 |
887 | ```js
888 | const redFruit = $('')
889 | $('.apple').wrap(redFruit)
890 |
891 | //=>
913 | ```
914 |
915 | #### .css( [propertyName] ) .css( [ propertyNames] ) .css( [propertyName], [value] ) .css( [propertyName], [function] ) .css( [properties] )
916 |
917 | Get the value of a style property for the first element in the set of matched elements or set one or more CSS properties for every matched element.
918 |
919 | ### Rendering
920 | When you're ready to render the document, you can use the `html` utility function:
921 |
922 | ```js
923 | $.html()
924 | //=>
925 | //
Apple
926 | //
Orange
927 | //
Pear
928 | //
929 | ```
930 |
931 | If you want to return the outerHTML you can use `$.html(selector)`:
932 |
933 | ```js
934 | $.html('.pear')
935 | //=>
Pear
936 | ```
937 |
938 | By default, `html` will leave some tags open. Sometimes you may instead want to render a valid XML document. For example, you might parse the following XML snippet:
939 |
940 | ```xml
941 | const $ = cheerio.load('');
942 | ```
943 |
944 | ... and later want to render to XML. To do this, you can use the 'xml' utility function:
945 |
946 | ```js
947 | $.xml()
948 | //=>
949 | ```
950 |
951 | You may also render the text content of a Cheerio object using the `text` static method:
952 |
953 | ```js
954 | const $ = cheerio.load('This is content.')
955 | $.text()
956 | //=> This is content.
957 | ```
958 |
959 | The method may be called on the Cheerio module itself--be sure to pass a collection of nodes!
960 |
961 | ```js
962 | const $ = cheerio.load('
This is content.
')
963 | cheerio.text($('div'))
964 | //=> This is content.
965 | ```
966 |
967 | ### Miscellaneous
968 | DOM element methods that don't fit anywhere else
969 |
970 | #### .toArray()
971 | Retrieve all the DOM elements contained in the jQuery set as an array.
972 |
973 | ```js
974 | $('li').toArray()
975 | //=> [ {...}, {...}, {...} ]
976 | ```
977 |
978 | #### .clone() ####
979 | Clone the cheerio object.
980 |
981 | ```js
982 | const moreFruit = $('#fruits').clone()
983 | ```
984 |
985 | ### Utilities
986 |
987 | #### $.root
988 |
989 | Sometimes you need to work with the top-level root element. To query it, you can use `$.root()`.
990 |
991 | ```js
992 | $.root().append('
').html();
993 | //=>
...
994 | ```
995 |
996 | #### $.contains( container, contained )
997 | Checks to see if the `contained` DOM element is a descendant of the `container` DOM element.
998 |
999 | #### $.parseHTML( data [, context ] [, keepScripts ] )
1000 | Parses a string into an array of DOM nodes. The `context` argument has no meaning for Cheerio, but it is maintained for API compatibility.
1001 |
1002 | #### $.load( html[, options ] )
1003 | Load in the HTML. (See the previous section titled "Loading" for more information.)
1004 |
1005 | ### Plugins
1006 |
1007 | Once you have loaded a document, you may extend the prototype or the equivalent `fn` property with custom plugin methods:
1008 |
1009 | ```js
1010 | const $ = cheerio.load('Hello, world!');
1011 | $.prototype.logHtml = function() {
1012 | console.log(this.html());
1013 | };
1014 |
1015 | $('body').logHtml(); // logs "Hello, world!" to the console
1016 | ```
1017 |
1018 | ### The "DOM Node" object
1019 |
1020 | Cheerio collections are made up of objects that bear some resemblance to [browser-based DOM nodes](https://developer.mozilla.org/en-US/docs/Web/API/Node). You can expect them to define the following properties:
1021 |
1022 | - `tagName`
1023 | - `parentNode`
1024 | - `previousSibling`
1025 | - `nextSibling`
1026 | - `nodeValue`
1027 | - `firstChild`
1028 | - `childNodes`
1029 | - `lastChild`
1030 |
1031 | ## Screencasts
1032 |
1033 | http://vimeo.com/31950192
1034 |
1035 | > This video tutorial is a follow-up to Nettut's "How to Scrape Web Pages with Node.js and jQuery", using cheerio instead of JSDOM + jQuery. This video shows how easy it is to use cheerio and how much faster cheerio is than JSDOM + jQuery.
1036 |
1037 | ## Contributors
1038 |
1039 | These are some of the contributors that have made cheerio possible:
1040 |
1041 | ```
1042 | project : cheerio
1043 | repo age : 2 years, 6 months
1044 | active : 285 days
1045 | commits : 762
1046 | files : 36
1047 | authors :
1048 | 293 Matt Mueller 38.5%
1049 | 133 Matthew Mueller 17.5%
1050 | 92 Mike Pennisi 12.1%
1051 | 54 David Chambers 7.1%
1052 | 30 kpdecker 3.9%
1053 | 19 Felix Böhm 2.5%
1054 | 17 fb55 2.2%
1055 | 15 Siddharth Mahendraker 2.0%
1056 | 11 Adam Bretz 1.4%
1057 | 8 Nazar Leush 1.0%
1058 | 7 ironchefpython 0.9%
1059 | 6 Jarno Leppänen 0.8%
1060 | 5 Ben Sheldon 0.7%
1061 | 5 Jos Shepherd 0.7%
1062 | 5 Ryan Schmukler 0.7%
1063 | 5 Steven Vachon 0.7%
1064 | 4 Maciej Adwent 0.5%
1065 | 4 Amir Abu Shareb 0.5%
1066 | 3 jeremy.dentel@brandingbrand.com 0.4%
1067 | 3 Andi Neck 0.4%
1068 | 2 steve 0.3%
1069 | 2 alexbardas 0.3%
1070 | 2 finspin 0.3%
1071 | 2 Ali Farhadi 0.3%
1072 | 2 Chris Khoo 0.3%
1073 | 2 Rob Ashton 0.3%
1074 | 2 Thomas Heymann 0.3%
1075 | 2 Jaro Spisak 0.3%
1076 | 2 Dan Dascalescu 0.3%
1077 | 2 Torstein Thune 0.3%
1078 | 2 Wayne Larsen 0.3%
1079 | 1 Timm Preetz 0.1%
1080 | 1 Xavi 0.1%
1081 | 1 Alex Shaindlin 0.1%
1082 | 1 mattym 0.1%
1083 | 1 Felix Böhm 0.1%
1084 | 1 Farid Neshat 0.1%
1085 | 1 Dmitry Mazuro 0.1%
1086 | 1 Jeremy Hubble 0.1%
1087 | 1 nevermind 0.1%
1088 | 1 Manuel Alabor 0.1%
1089 | 1 Matt Liegey 0.1%
1090 | 1 Chris O'Hara 0.1%
1091 | 1 Michael Holroyd 0.1%
1092 | 1 Michiel De Mey 0.1%
1093 | 1 Ben Atkin 0.1%
1094 | 1 Rich Trott 0.1%
1095 | 1 Rob "Hurricane" Ashton 0.1%
1096 | 1 Robin Gloster 0.1%
1097 | 1 Simon Boudrias 0.1%
1098 | 1 Sindre Sorhus 0.1%
1099 | 1 xiaohwan 0.1%
1100 | ```
1101 |
1102 | ## Cheerio in the real world
1103 |
1104 | Are you using cheerio in production? Add it to the [wiki](https://github.com/cheeriojs/cheerio/wiki/Cheerio-in-Production)!
1105 |
1106 | ## Testing
1107 |
1108 | To run the test suite, download the repository, then within the cheerio directory, run:
1109 |
1110 | ```shell
1111 | make setup
1112 | make test
1113 | ```
1114 |
1115 | This will download the development packages and run the test suite.
1116 |
1117 | ## Special Thanks
1118 |
1119 | This library stands on the shoulders of some incredible developers. A special thanks to:
1120 |
1121 | __• @FB55 for node-htmlparser2 & CSSSelect:__
1122 | Felix has a knack for writing speedy parsing engines. He completely re-wrote both @tautologistic's `node-htmlparser` and @harry's `node-soupselect` from the ground up, making both of them much faster and more flexible. Cheerio would not be possible without his foundational work
1123 |
1124 | __• @jQuery team for jQuery:__
1125 | The core API is the best of its class and despite dealing with all the browser inconsistencies the code base is extremely clean and easy to follow. Much of cheerio's implementation and documentation is from jQuery. Thanks guys.
1126 |
1127 | __• @visionmedia:__
1128 | The style, the structure, the open-source"-ness" of this library comes from studying TJ's style and using many of his libraries. This dude consistently pumps out high-quality libraries and has always been more than willing to help or answer questions. You rock TJ.
1129 |
1130 | ## License
1131 |
1132 | MIT
1133 |
--------------------------------------------------------------------------------