【问题标题】:Get the id of the parent (li) with its content (span). CHEERIO获取父级 (li) 的 id 及其内容 (span)。凯里奥
【发布时间】:2021-12-20 02:37:15
【问题描述】:

我这里有一个代码,是通过抓取页面获得的:

<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>

我想用cheerio 或只是Vanilla JS 来查找父级的ID (li) 及其内容(span)。

例子:

  • 检测跨度元素TV
  • 获取其父级的 id(此处为 option-2
  • 返回值 data-nume

提前谢谢你。

【问题讨论】:

    标签: javascript html node.js cheerio


    【解决方案1】:

    尝试使用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);
    

    工作演示

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

    【讨论】:

      猜你喜欢
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      • 2014-01-19
      • 2020-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多