Home > Software engineering >  Get the id of the parent (li) with its content (span). CHEERIO
Get the id of the parent (li) with its content (span). CHEERIO

Time:11-06

I have a code here which I got by scraping a page:

<div>
    <ul id="options">
        <li id="option-1" data-nume="1">
            <span class="title">Book</span>
            <span class="site">fnac.com</span>
        </li>
        <li id="option-2" data-nume="2">
            <span class="title">TV</span>
            <span class="site">youtube.com</span>
        </li>
    </ul>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

And I would like with cheerio or just Vanilla JS to find the id of the parent (li) with its content (span).

Example:

  • Detect the span element TV
  • Take the id of its parent (here option-2)
  • Return the value data-nume.

Thank you in advance.

CodePudding user response:

Try using filter()

https://api.jquery.com/filter/#filter-selector

const $tv = $('#options .title').filter(function() {
  return $(this).text().trim().toLowerCase() === 'tv';
});

const tvNume = $tv.parent('[data-nume]').data('nume');

console.log(tvNume);

Working Demo

https://codesandbox.io/s/ecstatic-tree-6hez6?file=/src/index.js

  • Related