Skip to content
Advertisement

How to parse multiple div with same class name in a div in cheerio?

I have “n” number of classes with className: “classparent” In which I have “n” number of classes with className: “class1” which consists of “n” number of div’s with className: “class2”

How can I parse each and every of these div.class2 and get their style property in cheerio ???

Currently I am doing this :

$(".classParent").each((i, el) => {
    prop[i] = $(el).find(".class1 .class2").attr("style")
})

It returns me only one div.class2 from every .class1.

I want results like this:

[
 {}, // 1st object which contains all style properties of .class2 of 1st .class1
 {}, // 2nd object which contains all style properties of .class2 of 2nd .class1
 {}, // 3rd object which contains all style properties of .class2 of 3rd .class1
 ...
]

And this is how my objects would look like:

{
 "style attribute value",
 "style attribute value",
 "style attribute value",
 ......
}

Advertisement

Answer

You can use the toArray function:

$(".classParent").each((i, el) => {
    prop[i] = $(el)
        .find(".class1 .class2")
        .toArray()
        .map($)
        .map(d => d.attr("style"));
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement