Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cheerio / jquery selectors: how to get text in tag a?

Tags:

cheerio

I am trying to access links on a website. The website looks like the first code sample and the links are in different div-containers:

<div id="list">
  <div class="class1">
    <div class="item-class1">
      <a href="http://www.example.com/1">example1</a>
    </div>
  </div>
  <div class="class2">
    <div class="item-class2">
      <a href="http://www.example.com/2">example2</a>
    </div>
  </div>
</div>

I did tried to extract the links with this code:

var list = [];
$('div[id="list"]').find('a').each(function (index, element) {
  list.push($(element).attr('href'));
});

But the outputs look like this:

0: "http://www.example.com/1"
1: "http://www.example.com/2"

But I want it to look like this:

0: example1
1: example2

Thank you very much.

like image 815
Worapol Pragobkit Avatar asked Dec 18 '22 01:12

Worapol Pragobkit


1 Answers

$(element).attr('href') ==> get href property : the link

$(element).text() ==> get text

just change like this :

var list = [];
    $('div[id="list"]').find('a').each(function (index, element) {
      list.push($(element).text());
    });
like image 195
Taha Azzabi Avatar answered Mar 23 '23 05:03

Taha Azzabi