Search code examples
node.jsjquery-selectorscheerio

Cheerio how to get text nodes sibling with other tag


i have solved this before long ago, but i forgot now. How i can access that date when my main selector is

$('.date')

let cheerio = require('cheerio')
let html = `
<html>
    <body>
        <span class="date">
            <span class="category">Article</span>
            Sat, 22 Jan 2021 11:12
        </span>
    </body>
</html>`

let $ = cheerio.load(html)

// Empty
console.log($('.date').next().text())
// Empty
console.log($($('.date').children()[0]).next().next().text())
// Empty
console.log($($('.date').children()[0]).next().text())
// Empty
$('.date').each(el => { console.log($(el).text())})

Solution

  • Further to comment by @Dario:

    The contents() function:

    Gets the children of each element in the set of matched elements, including text and comment nodes.

    So you can do this:

    let cheerio = require('cheerio')
    let html = `
    <html>
        <body>
            <span class="date">
                <span class="category">Article</span>
                Sat, 22 Jan 2021 11:12
            </span>
        </body>
    </html>`
    
    let $ = cheerio.load(html)
    
    let val = $('.date').contents().last().text()
    
    console.log(val.trim())
    // prints Sat, 22 Jan 2021 11:12