node.jsweb-scrapingcheerio

CheerioJS get specific <li> where header text 'What I Want'


I'm trying to get li elements where the header is 'What I want'

This is my Code:

let wants = []
                $$('li').each((wantIdx, wantElement) => {
                    const want= $(relatedArticleElement).text()
                    wants.push(want)
                })

and this is the HTML i'm trying to parse from:

<div class="side-list-panel">
    <h4 class="panel-header">What I Want</h4>
    <ul class="panel-items-list">
        <li>
            1
        </li>
        <li>
            2
        </li>
        <li>
            3
        </li>
        <li>
                4
        </li>
        <li>
            5
        </li>
    </ul>
</div>
<div class="side-list-panel">
    <h4 class="panel-header">What I don't want</h4>
    <ul class="panel-items-list">
        <li>
            a
        </li>
        <li>
            b
        </li>
        <li>
            c
        </li>
        <li>
            d
        </li>
        <li>
            e
        </li>
    </ul>
</div>

this code gets me every single li elements in the page obviously, is there any way i can only get the lis under the 'What I Want' panel-header?


Solution

  • You can get those with:

    $('h4:contains("What I Want") + ul li').get().map(li => $(li).text())