Search code examples
javascriptjqueryweb-scrapingcheerio

Cheerio - How to get the value of all elements with same attribute and not the content /text?


I am trying to get not the content of the element with a specific attribute but the attributes value!

when I do the following:

const time =  $item.find('div').find('p').find('time')
time.attr('datetime')

I only get 1 value and not all the values with same attribute.

if I do this:

     $item.find('div').find('p').find('time').text()

I get all the contents with same attribute, however, I dont want the text, just the value of attribute.

The html structure is the following:

<div id="main">
   <div class="layout-stack">
      <ul>
        <li> 
            <ul>
               <li>
                 <div></div>
                 <div>
                   <div></div>
                   <p></p>
                   <p>
                       <time dateTime="2022-11-09T07:18:05.000Z"> //thats what I want
                         "09.11.2022, 08:18" //that I dont want
                         "&nbsp;"
                         "Uhr"
                       </time>
                   </p>
                 </div>
               </li>
               <li></li>
               <li></li>
               ...
           </ul>
        </li>
      </ul>
   </div>
</div>

my code in general gets all items of that ul list (for other elements) and I just cant get teh attribute value

...
 $('#main .layout-stack > ul > li > ul')
            .map((_, item) => {
                const $item = $(item);
                //here I access the elements 
             return {}
            }).toArray()
...

Solution

  • Try this:

    const times = $('#main time').map((_, time) => $(time).attr('datetime')).get();
    console.log(times);