Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get node line number in cheerio.js?

I am using cheerio.js as per below:

var $ = cheerio.load(html,{withStartIndices : true});

When I use console.log($('#element1'));. It will return node with the character position.

   { 
     type: 'tag',
     name: 'h6',
     attribs: { align: 'center', id: 'r' },
     children: [ [Object] ],
     next: null,
     startIndex: 310,
.......

Is there any way to get the line number in cheerio.js for a specific element?

like image 557
Shalitha Suranga Avatar asked Jan 01 '26 18:01

Shalitha Suranga


1 Answers

Here's one solution

const $ = cheerio.load(html, { withStartIndices: true });
const start = $('#element1').get(0).startIndex;
const lineNumber = html.substr(0, start).split('\n').length;
like image 122
Trevor Avatar answered Jan 03 '26 10:01

Trevor



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!