0

I am trying to get the list of elements inside a particular div as in this example. However the element I am trying to find doesnt have any attributes but can be located using the following xpath //*[@id="main"]/div[4]/div.

I tried using $('div[id="main"]/div[4]/div'). but it doesnot work. any suggestions?

example code below:-

const cheerio = require('cheerio');
const fs = require("fs");

const body = fs.readFileSync("check.html");
const $ = cheerio.load(body);


var list = [];
$('div[id="main"]').find('div > a').each(function (index, element) {
  list.push($(element).attr('href'));
});



console.dir(list.length);

In the example above is getting everything from inside div#main so the number of elements with a tags is much larger than the targeted div by the xpath. what should be the cheerio equivalent query?

isnvi23h4
  • 1,910
  • 1
  • 27
  • 45

1 Answers1

2

convert xpath to css. target fourth child div and all its div's ahref children right away:

$('div[id="main"] > div:nth-of-type(4) > div > a').each(function (index, element) {
    list.push($(element).attr('href'));
});
traynor
  • 5,490
  • 3
  • 13
  • 23