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 !
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 !
- try adding the index of the element you want .get(0) – gustavozapata Commented Sep 12, 2020 at 9:13
-
the class you are selecting is
panel-items-list
but its actuallypanel-item-list
in your HTML.... – Always Helping Commented Sep 12, 2020 at 9:15 - Your '.panel-items-list' selector doesn't meet any of the elements you present in the markup, could you had more context to the example? – ArnaudV Commented Sep 12, 2020 at 9:17
2 Answers
Reset to default 4To 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./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()