Search code examples
javascripthtmljqueryjquery-selectorscheerio

How to get select value of a HREF element through Cheerio


I have a HTML source.

<div class="placeholderClass">
    <h2>THIS IS A PLACEHOLDER</h2> <br>
    <p>I want to redirect you to my website over here <a href="https://www.placeholder.com/path/app/stores/HubArticleView?hubId=Hub-100000&amp;placeHoldingID=100000&amp;userID=10000&amp;nameID=40&amp;viewID=10000#parentHorizontalTab2">PLACEHOLDER VIEW</a>.
    </p>
</div>

I want to get the href element from this source


const $ = cheerio.load(body); // body is the HTML that is loaded above
const IDInfo = {};

const HREF = $('.placeholderClass > h2 > br > p[href])

I'm doing the last line to try and get the HREF link so I cant extract it.


Solution

  • This is fundamental thing about css selectors and jQuery/Cheerio. The attribute selector don't return attribute but node. What you want is this:

    $('.placeholderClass > h2 > br > p[href]').attr('href');