Skip to content
the poor coder

cheerio get href text

Poor Man
Published
Reading time
1 min read
On this page

Cheerio get href text#

As a blogger, I often need to extract information from HTML pages to create content for my website. One common task is to get the text of a hyperlink, or anchor, element using Cheerio.

Using Cheerio to Get Href Text#

Cheerio is a fast and flexible library for parsing HTML and XML documents. It provides a simple and intuitive API for navigating and manipulating the document tree. To get the text of an anchor element using Cheerio, you can use the text() method.

JavaScript

const cheerio = require('cheerio');
const html = '<div><a href="https://www.example.com">Example</a></div>';
const $ = cheerio.load(html);
const text = $('a').text();
console.log(text); // Output: Example

In this example, we first load an HTML string into Cheerio using the load() method. We then find the anchor element using the selector 'a' and call the text() method to get its text content.

Using Cheerio to Get Href Attribute#

Sometimes, we may also need to get the value of the href attribute of an anchor element. We can use the attr() method for this purpose.

JavaScript

const cheerio = require('cheerio');
const html = '<div><a href="https://www.example.com">Example</a></div>';
const $ = cheerio.load(html);
const href = $('a').attr('href');
console.log(href); // Output: https://www.example.com

In this example, we again load the HTML string into Cheerio and find the anchor element using the selector 'a'. We then call the attr() method with the argument 'href' to get the value of the href attribute.

Conclusion#

Cheerio is a powerful tool for parsing and manipulating HTML and XML documents. With its simple and intuitive API, we can easily extract information from web pages and use it to create engaging content.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC