You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Readme.md 38KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  1. <h1 align="center">cheerio</h1>
  2. <h5 align="center">Fast, flexible & lean implementation of core jQuery designed specifically for the server.</h5>
  3. <div align="center">
  4. <a href="http://travis-ci.org/cheeriojs/cheerio">
  5. <img src="https://secure.travis-ci.org/cheeriojs/cheerio.svg?branch=master" alt="Travis CI" />
  6. </a>
  7. <a href="https://coveralls.io/r/cheeriojs/cheerio">
  8. <img src="http://img.shields.io/coveralls/cheeriojs/cheerio.svg?branch=master&style=flat" alt="Coverage" />
  9. </a>
  10. <a href="https://gitter.im/cheeriojs/cheerio?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge">
  11. <img src="https://badges.gitter.im/Join%20Chat.svg" alt="Join the chat at https://gitter.im/cheeriojs/cheerio" />
  12. </a>
  13. <a href="#backers">
  14. <img src="https://opencollective.com/cheerio/backers/badge.svg" alt="OpenCollective backers"/>
  15. </a>
  16. <a href="#sponsors">
  17. <img src="https://opencollective.com/cheerio/sponsors/badge.svg" alt="OpenCollective sponsors"/>
  18. </a>
  19. </div>
  20. <br />
  21. ```js
  22. let cheerio = require('cheerio')
  23. let $ = cheerio.load('<h2 class="title">Hello world</h2>')
  24. $('h2.title').text('Hello there!')
  25. $('h2').addClass('welcome')
  26. $.html()
  27. //=> <h2 class="title welcome">Hello there!</h2>
  28. ```
  29. ## Installation
  30. `npm install cheerio`
  31. ## Features
  32. __&#10084; Familiar syntax:__
  33. 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.
  34. __&#991; Blazingly fast:__
  35. 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.
  36. __&#10049; Incredibly flexible:__
  37. Cheerio wraps around @FB55's forgiving [htmlparser2](https://github.com/fb55/htmlparser2/). Cheerio can parse nearly any HTML or XML document.
  38. ## Sponsors
  39. Does your company use Cheerio in production? Please consider [sponsoring this project](https://opencollective.com/cheerio#sponsor). Your help will allow maintainers to dedicate more time and resources to its development and support.
  40. <a href="https://opencollective.com/cheerio/sponsor/0/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/0/avatar.svg"></a>
  41. <a href="https://opencollective.com/cheerio/sponsor/1/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/1/avatar.svg"></a>
  42. <a href="https://opencollective.com/cheerio/sponsor/2/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/2/avatar.svg"></a>
  43. <a href="https://opencollective.com/cheerio/sponsor/3/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/3/avatar.svg"></a>
  44. <a href="https://opencollective.com/cheerio/sponsor/4/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/4/avatar.svg"></a>
  45. <a href="https://opencollective.com/cheerio/sponsor/5/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/5/avatar.svg"></a>
  46. <a href="https://opencollective.com/cheerio/sponsor/6/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/6/avatar.svg"></a>
  47. <a href="https://opencollective.com/cheerio/sponsor/7/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/7/avatar.svg"></a>
  48. <a href="https://opencollective.com/cheerio/sponsor/8/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/8/avatar.svg"></a>
  49. <a href="https://opencollective.com/cheerio/sponsor/9/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/9/avatar.svg"></a>
  50. <a href="https://opencollective.com/cheerio/sponsor/10/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/10/avatar.svg"></a>
  51. <a href="https://opencollective.com/cheerio/sponsor/11/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/11/avatar.svg"></a>
  52. <a href="https://opencollective.com/cheerio/sponsor/12/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/12/avatar.svg"></a>
  53. <a href="https://opencollective.com/cheerio/sponsor/13/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/13/avatar.svg"></a>
  54. <a href="https://opencollective.com/cheerio/sponsor/14/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/14/avatar.svg"></a>
  55. <a href="https://opencollective.com/cheerio/sponsor/15/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/15/avatar.svg"></a>
  56. <a href="https://opencollective.com/cheerio/sponsor/16/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/16/avatar.svg"></a>
  57. <a href="https://opencollective.com/cheerio/sponsor/17/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/17/avatar.svg"></a>
  58. <a href="https://opencollective.com/cheerio/sponsor/18/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/18/avatar.svg"></a>
  59. <a href="https://opencollective.com/cheerio/sponsor/19/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/19/avatar.svg"></a>
  60. <a href="https://opencollective.com/cheerio/sponsor/20/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/20/avatar.svg"></a>
  61. <a href="https://opencollective.com/cheerio/sponsor/21/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/21/avatar.svg"></a>
  62. <a href="https://opencollective.com/cheerio/sponsor/22/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/22/avatar.svg"></a>
  63. <a href="https://opencollective.com/cheerio/sponsor/23/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/23/avatar.svg"></a>
  64. <a href="https://opencollective.com/cheerio/sponsor/24/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/24/avatar.svg"></a>
  65. <a href="https://opencollective.com/cheerio/sponsor/25/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/25/avatar.svg"></a>
  66. <a href="https://opencollective.com/cheerio/sponsor/26/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/26/avatar.svg"></a>
  67. <a href="https://opencollective.com/cheerio/sponsor/27/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/27/avatar.svg"></a>
  68. <a href="https://opencollective.com/cheerio/sponsor/28/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/28/avatar.svg"></a>
  69. <a href="https://opencollective.com/cheerio/sponsor/29/website" target="_blank"><img src="https://opencollective.com/cheerio/sponsor/29/avatar.svg"></a>
  70. ## Backers
  71. [Become a backer](https://opencollective.com/cheerio#backer) to show your support for Cheerio and help us maintain and improve this open source project.
  72. <a href="https://opencollective.com/cheerio/backer/0/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/0/avatar.svg"></a>
  73. <a href="https://opencollective.com/cheerio/backer/1/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/1/avatar.svg"></a>
  74. <a href="https://opencollective.com/cheerio/backer/2/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/2/avatar.svg"></a>
  75. <a href="https://opencollective.com/cheerio/backer/3/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/3/avatar.svg"></a>
  76. <a href="https://opencollective.com/cheerio/backer/4/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/4/avatar.svg"></a>
  77. <a href="https://opencollective.com/cheerio/backer/5/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/5/avatar.svg"></a>
  78. <a href="https://opencollective.com/cheerio/backer/6/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/6/avatar.svg"></a>
  79. <a href="https://opencollective.com/cheerio/backer/7/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/7/avatar.svg"></a>
  80. <a href="https://opencollective.com/cheerio/backer/8/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/8/avatar.svg"></a>
  81. <a href="https://opencollective.com/cheerio/backer/9/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/9/avatar.svg"></a>
  82. <a href="https://opencollective.com/cheerio/backer/10/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/10/avatar.svg"></a>
  83. <a href="https://opencollective.com/cheerio/backer/11/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/11/avatar.svg"></a>
  84. <a href="https://opencollective.com/cheerio/backer/12/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/12/avatar.svg"></a>
  85. <a href="https://opencollective.com/cheerio/backer/13/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/13/avatar.svg"></a>
  86. <a href="https://opencollective.com/cheerio/backer/14/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/14/avatar.svg"></a>
  87. <a href="https://opencollective.com/cheerio/backer/15/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/15/avatar.svg"></a>
  88. <a href="https://opencollective.com/cheerio/backer/16/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/16/avatar.svg"></a>
  89. <a href="https://opencollective.com/cheerio/backer/17/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/17/avatar.svg"></a>
  90. <a href="https://opencollective.com/cheerio/backer/18/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/18/avatar.svg"></a>
  91. <a href="https://opencollective.com/cheerio/backer/19/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/19/avatar.svg"></a>
  92. <a href="https://opencollective.com/cheerio/backer/20/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/20/avatar.svg"></a>
  93. <a href="https://opencollective.com/cheerio/backer/21/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/21/avatar.svg"></a>
  94. <a href="https://opencollective.com/cheerio/backer/22/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/22/avatar.svg"></a>
  95. <a href="https://opencollective.com/cheerio/backer/23/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/23/avatar.svg"></a>
  96. <a href="https://opencollective.com/cheerio/backer/24/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/24/avatar.svg"></a>
  97. <a href="https://opencollective.com/cheerio/backer/25/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/25/avatar.svg"></a>
  98. <a href="https://opencollective.com/cheerio/backer/26/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/26/avatar.svg"></a>
  99. <a href="https://opencollective.com/cheerio/backer/27/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/27/avatar.svg"></a>
  100. <a href="https://opencollective.com/cheerio/backer/28/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/28/avatar.svg"></a>
  101. <a href="https://opencollective.com/cheerio/backer/29/website" target="_blank"><img src="https://opencollective.com/cheerio/backer/29/avatar.svg"></a>
  102. ## API
  103. ### Markup example we'll be using:
  104. ```html
  105. <ul id="fruits">
  106. <li class="apple">Apple</li>
  107. <li class="orange">Orange</li>
  108. <li class="pear">Pear</li>
  109. </ul>
  110. ```
  111. This is the HTML markup we will be using in all of the API examples.
  112. ### Loading
  113. 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.
  114. This is the _preferred_ method:
  115. ```js
  116. var cheerio = require('cheerio'),
  117. $ = cheerio.load('<ul id="fruits">...</ul>');
  118. ```
  119. Optionally, you can also load in the HTML by passing the string as the context:
  120. ```js
  121. $ = require('cheerio');
  122. $('ul', '<ul id="fruits">...</ul>');
  123. ```
  124. Or as the root:
  125. ```js
  126. $ = require('cheerio');
  127. $('li', 'ul', '<ul id="fruits">...</ul>');
  128. ```
  129. You can also pass an extra object to `.load()` if you need to modify any
  130. of the default parsing options:
  131. ```js
  132. $ = cheerio.load('<ul id="fruits">...</ul>', {
  133. normalizeWhitespace: true,
  134. xmlMode: true
  135. });
  136. ```
  137. 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:
  138. ```js
  139. {
  140. withDomLvl1: true,
  141. normalizeWhitespace: false,
  142. xmlMode: false,
  143. decodeEntities: true
  144. }
  145. ```
  146. For a full list of options and their effects, see [this](https://github.com/fb55/DomHandler) and
  147. [htmlparser2's options](https://github.com/fb55/htmlparser2/wiki/Parser-options).
  148. ### Selectors
  149. Cheerio's selector implementation is nearly identical to jQuery's, so the API is very similar.
  150. #### $( selector, [context], [root] )
  151. `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.
  152. 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.
  153. ```js
  154. $('.apple', '#fruits').text()
  155. //=> Apple
  156. $('ul .pear').attr('class')
  157. //=> pear
  158. $('li[class=orange]').html()
  159. //=> Orange
  160. ```
  161. ### Attributes
  162. Methods for getting and modifying attributes.
  163. #### .attr( name, value )
  164. 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.
  165. ```js
  166. $('ul').attr('id')
  167. //=> fruits
  168. $('.apple').attr('id', 'favorite').html()
  169. //=> <li class="apple" id="favorite">Apple</li>
  170. ```
  171. > See http://api.jquery.com/attr/ for more information
  172. #### .prop( name, value )
  173. Method for getting and setting properties. Gets the property value for only the first element in the matched set.
  174. ```js
  175. $('input[type="checkbox"]').prop('checked')
  176. //=> false
  177. $('input[type="checkbox"]').prop('checked', true).val()
  178. //=> ok
  179. ```
  180. > See http://api.jquery.com/prop/ for more information
  181. #### .data( name, value )
  182. Method for getting and setting data attributes. Gets or sets the data attribute value for only the first element in the matched set.
  183. ```js
  184. $('<div data-apple-color="red"></div>').data()
  185. //=> { appleColor: 'red' }
  186. $('<div data-apple-color="red"></div>').data('apple-color')
  187. //=> 'red'
  188. var apple = $('.apple').data('kind', 'mac')
  189. apple.data('kind')
  190. //=> 'mac'
  191. ```
  192. > See http://api.jquery.com/data/ for more information
  193. #### .val( [value] )
  194. Method for getting and setting the value of input, select, and textarea. Note: Support for `map`, and `function` has not been added yet.
  195. ```js
  196. $('input[type="text"]').val()
  197. //=> input_text
  198. $('input[type="text"]').val('test').html()
  199. //=> <input type="text" value="test"/>
  200. ```
  201. #### .removeAttr( name )
  202. Method for removing attributes by `name`.
  203. ```js
  204. $('.pear').removeAttr('class').html()
  205. //=> <li>Pear</li>
  206. ```
  207. #### .hasClass( className )
  208. Check to see if *any* of the matched elements have the given `className`.
  209. ```js
  210. $('.pear').hasClass('pear')
  211. //=> true
  212. $('apple').hasClass('fruit')
  213. //=> false
  214. $('li').hasClass('pear')
  215. //=> true
  216. ```
  217. #### .addClass( className )
  218. Adds class(es) to all of the matched elements. Also accepts a `function` like jQuery.
  219. ```js
  220. $('.pear').addClass('fruit').html()
  221. //=> <li class="pear fruit">Pear</li>
  222. $('.apple').addClass('fruit red').html()
  223. //=> <li class="apple fruit red">Apple</li>
  224. ```
  225. > See http://api.jquery.com/addClass/ for more information.
  226. #### .removeClass( [className] )
  227. 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.
  228. ```js
  229. $('.pear').removeClass('pear').html()
  230. //=> <li class="">Pear</li>
  231. $('.apple').addClass('red').removeClass().html()
  232. //=> <li class="">Apple</li>
  233. ```
  234. > See http://api.jquery.com/removeClass/ for more information.
  235. #### .toggleClass( className, [switch] )
  236. 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.
  237. ```js
  238. $('.apple.green').toggleClass('fruit green red').html()
  239. //=> <li class="apple fruit red">Apple</li>
  240. $('.apple.green').toggleClass('fruit green red', true).html()
  241. //=> <li class="apple green fruit red">Apple</li>
  242. ```
  243. > See http://api.jquery.com/toggleClass/ for more information.
  244. #### .is( selector )
  245. #### .is( element )
  246. #### .is( selection )
  247. #### .is( function(index) )
  248. 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.
  249. ### Forms
  250. #### .serializeArray()
  251. Encode a set of form elements as an array of names and values.
  252. ```js
  253. $('<form><input name="foo" value="bar" /></form>').serializeArray()
  254. //=> [ { name: 'foo', value: 'bar' } ]
  255. ```
  256. ### Traversing
  257. #### .find(selector)
  258. #### .find(selection)
  259. #### .find(node)
  260. Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
  261. ```js
  262. $('#fruits').find('li').length
  263. //=> 3
  264. $('#fruits').find($('.apple')).length
  265. //=> 1
  266. ```
  267. #### .parent([selector])
  268. Get the parent of each element in the current set of matched elements, optionally filtered by a selector.
  269. ```js
  270. $('.pear').parent().attr('id')
  271. //=> fruits
  272. ```
  273. #### .parents([selector])
  274. Get a set of parents filtered by `selector` of each element in the current set of match elements.
  275. ```js
  276. $('.orange').parents().length
  277. // => 2
  278. $('.orange').parents('#fruits').length
  279. // => 1
  280. ```
  281. #### .parentsUntil([selector][,filter])
  282. 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.
  283. ```js
  284. $('.orange').parentsUntil('#food').length
  285. // => 1
  286. ```
  287. #### .closest(selector)
  288. 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.
  289. ```js
  290. $('.orange').closest()
  291. // => []
  292. $('.orange').closest('.apple')
  293. // => []
  294. $('.orange').closest('li')
  295. // => [<li class="orange">Orange</li>]
  296. $('.orange').closest('#fruits')
  297. // => [<ul id="fruits"> ... </ul>]
  298. ```
  299. #### .next([selector])
  300. Gets the next sibling of the first selected element, optionally filtered by a selector.
  301. ```js
  302. $('.apple').next().hasClass('orange')
  303. //=> true
  304. ```
  305. #### .nextAll([selector])
  306. Gets all the following siblings of the first selected element, optionally filtered by a selector.
  307. ```js
  308. $('.apple').nextAll()
  309. //=> [<li class="orange">Orange</li>, <li class="pear">Pear</li>]
  310. $('.apple').nextAll('.orange')
  311. //=> [<li class="orange">Orange</li>]
  312. ```
  313. #### .nextUntil([selector], [filter])
  314. Gets all the following siblings up to but not including the element matched by the selector, optionally filtered by another selector.
  315. ```js
  316. $('.apple').nextUntil('.pear')
  317. //=> [<li class="orange">Orange</li>]
  318. ```
  319. #### .prev([selector])
  320. Gets the previous sibling of the first selected element optionally filtered by a selector.
  321. ```js
  322. $('.orange').prev().hasClass('apple')
  323. //=> true
  324. ```
  325. #### .prevAll([selector])
  326. Gets all the preceding siblings of the first selected element, optionally filtered by a selector.
  327. ```js
  328. $('.pear').prevAll()
  329. //=> [<li class="orange">Orange</li>, <li class="apple">Apple</li>]
  330. $('.pear').prevAll('.orange')
  331. //=> [<li class="orange">Orange</li>]
  332. ```
  333. #### .prevUntil([selector], [filter])
  334. Gets all the preceding siblings up to but not including the element matched by the selector, optionally filtered by another selector.
  335. ```js
  336. $('.pear').prevUntil('.apple')
  337. //=> [<li class="orange">Orange</li>]
  338. ```
  339. #### .slice( start, [end] )
  340. Gets the elements matching the specified range
  341. ```js
  342. $('li').slice(1).eq(0).text()
  343. //=> 'Orange'
  344. $('li').slice(1, 2).length
  345. //=> 1
  346. ```
  347. #### .siblings([selector])
  348. Gets the first selected element's siblings, excluding itself.
  349. ```js
  350. $('.pear').siblings().length
  351. //=> 2
  352. $('.pear').siblings('.orange').length
  353. //=> 1
  354. ```
  355. #### .children([selector])
  356. Gets the children of the first selected element.
  357. ```js
  358. $('#fruits').children().length
  359. //=> 3
  360. $('#fruits').children('.pear').text()
  361. //=> Pear
  362. ```
  363. #### .contents()
  364. Gets the children of each element in the set of matched elements, including text and comment nodes.
  365. ```js
  366. $('#fruits').contents().length
  367. //=> 3
  368. ```
  369. #### .each( function(index, element) )
  370. 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`.
  371. ```js
  372. var fruits = [];
  373. $('li').each(function(i, elem) {
  374. fruits[i] = $(this).text();
  375. });
  376. fruits.join(', ');
  377. //=> Apple, Orange, Pear
  378. ```
  379. #### .map( function(index, element) )
  380. 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.
  381. ```js
  382. $('li').map(function(i, el) {
  383. // this === el
  384. return $(this).text();
  385. }).get().join(' ');
  386. //=> "apple orange pear"
  387. ```
  388. #### .filter( selector ) <br /> .filter( selection ) <br /> .filter( element ) <br /> .filter( function(index) )
  389. 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.
  390. Selector:
  391. ```js
  392. $('li').filter('.orange').attr('class');
  393. //=> orange
  394. ```
  395. Function:
  396. ```js
  397. $('li').filter(function(i, el) {
  398. // this === el
  399. return $(this).attr('class') === 'orange';
  400. }).attr('class')
  401. //=> orange
  402. ```
  403. #### .not( selector ) <br /> .not( selection ) <br /> .not( element ) <br /> .not( function(index, elem) )
  404. 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.
  405. Selector:
  406. ```js
  407. $('li').not('.apple').length;
  408. //=> 2
  409. ```
  410. Function:
  411. ```js
  412. $('li').not(function(i, el) {
  413. // this === el
  414. return $(this).attr('class') === 'orange';
  415. }).length;
  416. //=> 2
  417. ```
  418. #### .has( selector ) <br /> .has( element )
  419. 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)')`.
  420. Selector:
  421. ```js
  422. $('ul').has('.pear').attr('id');
  423. //=> fruits
  424. ```
  425. Element:
  426. ```js
  427. $('ul').has($('.pear')[0]).attr('id');
  428. //=> fruits
  429. ```
  430. #### .first()
  431. Will select the first element of a cheerio object
  432. ```js
  433. $('#fruits').children().first().text()
  434. //=> Apple
  435. ```
  436. #### .last()
  437. Will select the last element of a cheerio object
  438. ```js
  439. $('#fruits').children().last().text()
  440. //=> Pear
  441. ```
  442. #### .eq( i )
  443. Reduce the set of matched elements to the one at the specified index. Use `.eq(-i)` to count backwards from the last selected element.
  444. ```js
  445. $('li').eq(0).text()
  446. //=> Apple
  447. $('li').eq(-1).text()
  448. //=> Pear
  449. ```
  450. #### .get( [i] )
  451. Retrieve the DOM elements matched by the Cheerio object. If an index is specified, retrieve one of the elements matched by the Cheerio object:
  452. ```js
  453. $('li').get(0).tagName
  454. //=> li
  455. ```
  456. If no index is specified, retrieve all elements matched by the Cheerio object:
  457. ```js
  458. $('li').get().length
  459. //=> 3
  460. ```
  461. #### .index()
  462. #### .index( selector )
  463. #### .index( nodeOrSelection )
  464. Search for a given element from among the matched elements.
  465. ```js
  466. $('.pear').index()
  467. //=> 2
  468. $('.orange').index('li')
  469. //=> 1
  470. $('.apple').index($('#fruit, li'))
  471. //=> 1
  472. ```
  473. #### .end()
  474. End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.
  475. ```js
  476. $('li').eq(0).end().length
  477. //=> 3
  478. ```
  479. #### .add( selector [, context] )
  480. #### .add( element )
  481. #### .add( elements )
  482. #### .add( html )
  483. #### .add( selection )
  484. Add elements to the set of matched elements.
  485. ```js
  486. $('.apple').add('.orange').length
  487. //=> 2
  488. ```
  489. #### .addBack( [filter] )
  490. Add the previous set of elements on the stack to the current set, optionally filtered by a selector.
  491. ```js
  492. $('li').eq(0).addBack('.orange').length
  493. //=> 2
  494. ```
  495. ### Manipulation
  496. Methods for modifying the DOM structure.
  497. #### .append( content, [content, ...] )
  498. Inserts content as the *last* child of each of the selected elements.
  499. ```js
  500. $('ul').append('<li class="plum">Plum</li>')
  501. $.html()
  502. //=> <ul id="fruits">
  503. // <li class="apple">Apple</li>
  504. // <li class="orange">Orange</li>
  505. // <li class="pear">Pear</li>
  506. // <li class="plum">Plum</li>
  507. // </ul>
  508. ```
  509. #### .appendTo( target )
  510. Insert every element in the set of matched elements to the end of the target.
  511. ```js
  512. $('<li class="plum">Plum</li>').appendTo('#fruits')
  513. $.html()
  514. //=> <ul id="fruits">
  515. // <li class="apple">Apple</li>
  516. // <li class="orange">Orange</li>
  517. // <li class="pear">Pear</li>
  518. // <li class="plum">Plum</li>
  519. // </ul>
  520. ```
  521. #### .prepend( content, [content, ...] )
  522. Inserts content as the *first* child of each of the selected elements.
  523. ```js
  524. $('ul').prepend('<li class="plum">Plum</li>')
  525. $.html()
  526. //=> <ul id="fruits">
  527. // <li class="plum">Plum</li>
  528. // <li class="apple">Apple</li>
  529. // <li class="orange">Orange</li>
  530. // <li class="pear">Pear</li>
  531. // </ul>
  532. ```
  533. #### .prependTo( target )
  534. Insert every element in the set of matched elements to the beginning of the target.
  535. ```js
  536. $('<li class="plum">Plum</li>').prependTo('#fruits')
  537. $.html()
  538. //=> <ul id="fruits">
  539. // <li class="plum">Plum</li>
  540. // <li class="apple">Apple</li>
  541. // <li class="orange">Orange</li>
  542. // <li class="pear">Pear</li>
  543. // </ul>
  544. ```
  545. #### .after( content, [content, ...] )
  546. Insert content next to each element in the set of matched elements.
  547. ```js
  548. $('.apple').after('<li class="plum">Plum</li>')
  549. $.html()
  550. //=> <ul id="fruits">
  551. // <li class="apple">Apple</li>
  552. // <li class="plum">Plum</li>
  553. // <li class="orange">Orange</li>
  554. // <li class="pear">Pear</li>
  555. // </ul>
  556. ```
  557. #### .insertAfter( target )
  558. Insert every element in the set of matched elements after the target.
  559. ```js
  560. $('<li class="plum">Plum</li>').insertAfter('.apple')
  561. $.html()
  562. //=> <ul id="fruits">
  563. // <li class="apple">Apple</li>
  564. // <li class="plum">Plum</li>
  565. // <li class="orange">Orange</li>
  566. // <li class="pear">Pear</li>
  567. // </ul>
  568. ```
  569. #### .before( content, [content, ...] )
  570. Insert content previous to each element in the set of matched elements.
  571. ```js
  572. $('.apple').before('<li class="plum">Plum</li>')
  573. $.html()
  574. //=> <ul id="fruits">
  575. // <li class="plum">Plum</li>
  576. // <li class="apple">Apple</li>
  577. // <li class="orange">Orange</li>
  578. // <li class="pear">Pear</li>
  579. // </ul>
  580. ```
  581. #### .insertBefore( target )
  582. Insert every element in the set of matched elements before the target.
  583. ```js
  584. $('<li class="plum">Plum</li>').insertBefore('.apple')
  585. $.html()
  586. //=> <ul id="fruits">
  587. // <li class="plum">Plum</li>
  588. // <li class="apple">Apple</li>
  589. // <li class="orange">Orange</li>
  590. // <li class="pear">Pear</li>
  591. // </ul>
  592. ```
  593. #### .remove( [selector] )
  594. Removes the set of matched elements from the DOM and all their children. `selector` filters the set of matched elements to be removed.
  595. ```js
  596. $('.pear').remove()
  597. $.html()
  598. //=> <ul id="fruits">
  599. // <li class="apple">Apple</li>
  600. // <li class="orange">Orange</li>
  601. // </ul>
  602. ```
  603. #### .replaceWith( content )
  604. Replaces matched elements with `content`.
  605. ```js
  606. var plum = $('<li class="plum">Plum</li>')
  607. $('.pear').replaceWith(plum)
  608. $.html()
  609. //=> <ul id="fruits">
  610. // <li class="apple">Apple</li>
  611. // <li class="orange">Orange</li>
  612. // <li class="plum">Plum</li>
  613. // </ul>
  614. ```
  615. #### .empty()
  616. Empties an element, removing all its children.
  617. ```js
  618. $('ul').empty()
  619. $.html()
  620. //=> <ul id="fruits"></ul>
  621. ```
  622. #### .html( [htmlString] )
  623. 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.
  624. ```js
  625. $('.orange').html()
  626. //=> Orange
  627. $('#fruits').html('<li class="mango">Mango</li>').html()
  628. //=> <li class="mango">Mango</li>
  629. ```
  630. #### .text( [textString] )
  631. 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.
  632. ```js
  633. $('.orange').text()
  634. //=> Orange
  635. $('ul').text()
  636. //=> Apple
  637. // Orange
  638. // Pear
  639. ```
  640. #### .wrap( content )
  641. 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.
  642. ```js
  643. var redFruit = $('<div class="red-fruit"></div>')
  644. $('.apple').wrap(redFruit)
  645. //=> <ul id="fruits">
  646. // <div class="red-fruit">
  647. // <li class="apple">Apple</li>
  648. // </div>
  649. // <li class="orange">Orange</li>
  650. // <li class="plum">Plum</li>
  651. // </ul>
  652. var healthy = $('<div class="healthy"></div>')
  653. $('li').wrap(healthy)
  654. //=> <ul id="fruits">
  655. // <div class="healthy">
  656. // <li class="apple">Apple</li>
  657. // </div>
  658. // <div class="healthy">
  659. // <li class="orange">Orange</li>
  660. // </div>
  661. // <div class="healthy">
  662. // <li class="plum">Plum</li>
  663. // </div>
  664. // </ul>
  665. ```
  666. #### .css( [propertName] ) <br /> .css( [ propertyNames] ) <br /> .css( [propertyName], [value] ) <br /> .css( [propertName], [function] ) <br /> .css( [properties] )
  667. 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.
  668. ### Rendering
  669. When you're ready to render the document, you can use the `html` utility function:
  670. ```js
  671. $.html()
  672. //=> <ul id="fruits">
  673. // <li class="apple">Apple</li>
  674. // <li class="orange">Orange</li>
  675. // <li class="pear">Pear</li>
  676. // </ul>
  677. ```
  678. If you want to return the outerHTML you can use `$.html(selector)`:
  679. ```js
  680. $.html('.pear')
  681. //=> <li class="pear">Pear</li>
  682. ```
  683. 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:
  684. ```xml
  685. $ = cheerio.load('<media:thumbnail url="http://www.foo.com/keyframe.jpg" width="75" height="50" time="12:05:01.123"/>');
  686. ```
  687. ... and later want to render to XML. To do this, you can use the 'xml' utility function:
  688. ```js
  689. $.xml()
  690. //=> <media:thumbnail url="http://www.foo.com/keyframe.jpg" width="75" height="50" time="12:05:01.123"/>
  691. ```
  692. You may also render the text content of a Cheerio object using the `text` static method:
  693. ```js
  694. $ = cheerio.load('This is <em>content</em>.')
  695. $.text()
  696. //=> This is content.
  697. ```
  698. The method may be called on the Cheerio module itself--be sure to pass a collection of nodes!
  699. ```js
  700. $ = cheerio.load('<div>This is <em>content</em>.</div>')
  701. cheerio.text($('div'))
  702. //=> This is content.
  703. ```
  704. ### Miscellaneous
  705. DOM element methods that don't fit anywhere else
  706. #### .toArray()
  707. Retrieve all the DOM elements contained in the jQuery set as an array.
  708. ```js
  709. $('li').toArray()
  710. //=> [ {...}, {...}, {...} ]
  711. ```
  712. #### .clone() ####
  713. Clone the cheerio object.
  714. ```js
  715. var moreFruit = $('#fruits').clone()
  716. ```
  717. ### Utilities
  718. #### $.root
  719. Sometimes you need to work with the top-level root element. To query it, you can use `$.root()`.
  720. ```js
  721. $.root().append('<ul id="vegetables"></ul>').html();
  722. //=> <ul id="fruits">...</ul><ul id="vegetables"></ul>
  723. ```
  724. #### $.contains( container, contained )
  725. Checks to see if the `contained` DOM element is a descendant of the `container` DOM element.
  726. #### $.parseHTML( data [, context ] [, keepScripts ] )
  727. Parses a string into an array of DOM nodes. The `context` argument has no meaning for Cheerio, but it is maintained for API compatability.
  728. #### $.load( html[, options ] )
  729. Load in the HTML. (See the previous section titled "Loading" for more information.)
  730. ### Plugins
  731. Once you have loaded a document, you may extend the prototype or the equivalent `fn` property with custom plugin methods:
  732. ```js
  733. var $ = cheerio.load('<html><body>Hello, <b>world</b>!</body></html>');
  734. $.prototype.logHtml = function() {
  735. console.log(this.html());
  736. };
  737. $('body').logHtml(); // logs "Hello, <b>world</b>!" to the console
  738. ```
  739. ### The "DOM Node" object
  740. Cheerio collections are made up of objects that bear some resemblence to [browser-based DOM nodes](https://developer.mozilla.org/en-US/docs/Web/API/Node). You can expect them to define the following properties:
  741. - `tagName`
  742. - `parentNode`
  743. - `previousSibling`
  744. - `nextSibling`
  745. - `nodeValue`
  746. - `firstChild`
  747. - `childNodes`
  748. - `lastChild`
  749. ## What about JSDOM?
  750. 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:
  751. __&#8226; JSDOM's built-in parser is too strict:__
  752. JSDOM's bundled HTML parser cannot handle many popular sites out there today.
  753. __&#8226; JSDOM is too slow:__
  754. Parsing big websites with JSDOM has a noticeable delay.
  755. __&#8226; JSDOM feels too heavy:__
  756. 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.
  757. ## When I would use JSDOM
  758. 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.
  759. ## Screencasts
  760. http://vimeo.com/31950192
  761. > 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.
  762. ## Contributors
  763. These are some of the contributors that have made cheerio possible:
  764. ```
  765. project : cheerio
  766. repo age : 2 years, 6 months
  767. active : 285 days
  768. commits : 762
  769. files : 36
  770. authors :
  771. 293 Matt Mueller 38.5%
  772. 133 Matthew Mueller 17.5%
  773. 92 Mike Pennisi 12.1%
  774. 54 David Chambers 7.1%
  775. 30 kpdecker 3.9%
  776. 19 Felix Böhm 2.5%
  777. 17 fb55 2.2%
  778. 15 Siddharth Mahendraker 2.0%
  779. 11 Adam Bretz 1.4%
  780. 8 Nazar Leush 1.0%
  781. 7 ironchefpython 0.9%
  782. 6 Jarno Leppänen 0.8%
  783. 5 Ben Sheldon 0.7%
  784. 5 Jos Shepherd 0.7%
  785. 5 Ryan Schmukler 0.7%
  786. 5 Steven Vachon 0.7%
  787. 4 Maciej Adwent 0.5%
  788. 4 Amir Abu Shareb 0.5%
  789. 3 jeremy.dentel@brandingbrand.com 0.4%
  790. 3 Andi Neck 0.4%
  791. 2 steve 0.3%
  792. 2 alexbardas 0.3%
  793. 2 finspin 0.3%
  794. 2 Ali Farhadi 0.3%
  795. 2 Chris Khoo 0.3%
  796. 2 Rob Ashton 0.3%
  797. 2 Thomas Heymann 0.3%
  798. 2 Jaro Spisak 0.3%
  799. 2 Dan Dascalescu 0.3%
  800. 2 Torstein Thune 0.3%
  801. 2 Wayne Larsen 0.3%
  802. 1 Timm Preetz 0.1%
  803. 1 Xavi 0.1%
  804. 1 Alex Shaindlin 0.1%
  805. 1 mattym 0.1%
  806. 1 Felix Böhm 0.1%
  807. 1 Farid Neshat 0.1%
  808. 1 Dmitry Mazuro 0.1%
  809. 1 Jeremy Hubble 0.1%
  810. 1 nevermind 0.1%
  811. 1 Manuel Alabor 0.1%
  812. 1 Matt Liegey 0.1%
  813. 1 Chris O'Hara 0.1%
  814. 1 Michael Holroyd 0.1%
  815. 1 Michiel De Mey 0.1%
  816. 1 Ben Atkin 0.1%
  817. 1 Rich Trott 0.1%
  818. 1 Rob "Hurricane" Ashton 0.1%
  819. 1 Robin Gloster 0.1%
  820. 1 Simon Boudrias 0.1%
  821. 1 Sindre Sorhus 0.1%
  822. 1 xiaohwan 0.1%
  823. ```
  824. ## Cheerio in the real world
  825. Are you using cheerio in production? Add it to the [wiki](https://github.com/cheeriojs/cheerio/wiki/Cheerio-in-Production)!
  826. ## Testing
  827. To run the test suite, download the repository, then within the cheerio directory, run:
  828. ```shell
  829. make setup
  830. make test
  831. ```
  832. This will download the development packages and run the test suite.
  833. ## Special Thanks
  834. This library stands on the shoulders of some incredible developers. A special thanks to:
  835. __&#8226; @FB55 for node-htmlparser2 & CSSSelect:__
  836. 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
  837. __&#8226; @jQuery team for jQuery:__
  838. 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.
  839. __&#8226; @visionmedia:__
  840. 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.
  841. ## License
  842. MIT