How to get the first class from two same classes with cheerio

Viewed 2939

currently i'm making a web scraper with node.Js using cheerio. i want to get the data inside the first of class="panel-items-list.

the html look like this

<div class="margin-bottom-=30">
  <div class="side-list-panel">
    <ul class="panel-item-list">...</ul>
  </div>
</div>
<div class="margin-bottom-=30">
  <div class="side-list-panel">
    <ul class="panel-item-list">...</ul>
  </div>
</div>

i already did like this

const relateArticle = $('.panel-items-list').map((i, section)=>{
                    let articles = $(section).find('h5');
                    return articles.text();

                }).get();

but it return the data from both class="panel-items-list". how do i get data just from one class ? sorry my english is bad. thanks in advance !

2 Answers

To get the first class only from the .panel-item-list use .get(0) that means you are only selecting the first index found using .map

Also, in your current code jQuery your are not selecting the right class selector.

In addition use .trim() method when getting the text to clean up any unseen spaces within the text.

Live Working Demo:

const relateArticle = $('.panel-item-list').map((i, section) => {
  let articles = $(section).find('h5');
  return articles.text().trim();
}).get(0)

console.log(relateArticle) //Foo
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="margin-bottom-=30">
  <div class="side-list-panel">
    <ul class="panel-item-list">
      <h5>
        Foo
      </h5>
    </ul>
  </div>
</div>
<div class="margin-bottom-=30">
  <div class="side-list-panel">
    <ul class="panel-item-list">
      <h5>
        Bar
      </h5>
    </ul>
  </div>
</div>

Use first():

$('.panel-items-list').first().find('h5').text()
Related