Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the get() function do in cheerio?

What is the difference between

$("h1")

and

$("h1").get()

The first one returns some sort of object and the second one an array (with the same elements), but what exactly does it do?

The documentation only mentions "Retrieve the DOM elements matched by the Cheerio object. If an index is specified, retrieve one of the elements matched by the Cheerio object", but it still isn't very clear to me...

like image 836
Nico Avatar asked Apr 27 '26 07:04

Nico


1 Answers

$("h1") results in a Cheerio object, on which Cheerio methods can be used (such as .get(), .text(), .prop(), and so on). Using .get() on a Cheerio object returns an array of underlying elements (not a Cheerio object), on which only methods that that element supports can be used - for example, instead of .text(), you would use .textContent, instead of .prop() you would use plain dot notation (eg instead of $('h1').prop('foo', 'bar'), $('h1').get()[0].foo = 'bar'). It's the same as jQuery's .get().

Cheerio objects are not DOM elements - .get() extracts an array of the latter from the former.

like image 75
CertainPerformance Avatar answered Apr 28 '26 22:04

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!