Skip to content

How to select values from li elements in Cheerio/jQuery?

<div class="tabs__content tabs__content--bg js-tab-panel">
<div class="tabs__panel tabs__panel--active">
   <div class="product__sizes-wrapper">
      <ul class="product__sizes-select js-size-select-list" data-locale="UK">
         <li class="product__sizes-option" data-msg="Sample Message" data-name="6"  data-value="060">
            <span class="product__sizes-size">
            <span class="product__sizes-size-1">6</span>
            <span class="product__sizes-size-2"></span>
            </span>
         </li>
         <li class="product__sizes-option" data-msg="Sample Message" data-name="7"  data-value="070">
            <span class="product__sizes-size">
            <span class="product__sizes-size-1">7</span>
            <span class="product__sizes-size-2"></span>
            </span>
         </li>
         <li class="product__sizes-option" data-msg="Sample Message" data-name="8"  data-value="080">
            <span class="product__sizes-size">
            <span class="product__sizes-size-1">8</span>
            <span class="product__sizes-size-2"></span>
            </span>
         </li>
         <li class="product__sizes-option" data-msg="Sample Message" data-name="9.5"  data-value="095">
            <span class="product__sizes-size">
            <span class="product__sizes-size-1">9.5</span>
            <span class="product__sizes-size-2"></span>
            </span>
         </li>
      </ul>
   </div>
</div>

I want to extract the values from the product__sizes-size-1 classes and transform them into an array. I have tried to use a .map() function to try and populate an array but it appears empty. To make it clear I want to have the array populated like [6,7,8,9.5] etc…

const sizes = $(".product__sizes-wrapper [data-locale = 'UK']").map(function() {
                        return $(this).text();
                     }).get();

Answer

Your approach is correct, you just use the wrong selector. Use product__sizes-size-1 instead:

$(document).ready(function(){
    var sizes = $('.product__sizes-size-1').map(function(){return $(this).text()}).get();
});