【问题标题】:cheerio - select two elements next to each otherCheerio - 选择两个相邻的元素
【发布时间】:2019-09-02 01:29:11
【问题描述】:

如何选择a元素,但只有当两个相邻?

<div>
 <a></a>     <---- without this one
 <irrelevant></irrelevant>
 <a></a>     <---- These two only
 <a></a>     <----
 <irrelevant></irrelevant>
 <a></a>     <---- and without these three
 <a></a>
 <a></a>
 <irrelevant></irrelevant>
 <a></a>     <---- and without this one 
</div>

【问题讨论】:

标签: jquery html node.js jquery-selectors cheerio


【解决方案1】:

我不知道cheerio,但在jQuery中你可以做到这一点(虽然它很老套而且很可怕):

$("div a").filter(function( index ) {
  var $this = $(this);
    return (
    $this.next("a").length>0 && //next is an a
    $this.next("a").next("a").length==0 &&  //next , next is not an a
    $this.prev("a").length==0 // prev is not an a
    ); 
  })
  .css( "background-color", "red" )
  .next("a")
  .css( "background-color", "red" );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
 <a>n</a> 
 <irrelevant></irrelevant>
 <a>y</a>
 <a>y</a>
 <irrelevant></irrelevant>
 <a>n</a>
 <a>n</a>
 <a>n</a>
 <irrelevant></irrelevant>
 <a>n</a>
</div>

【讨论】:

  • 实际上在 jQuery 中你可以这样做:$('a:has("+ a"):not(:has("+ a + a"))') - 但是在 Cheerio 中这行不通。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多