cheerio - 选择彼此相邻的两个元素

问题描述 投票:-1回答:1

如何选择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个回答
1
投票

我不知道cheerio,但在jQuery你可以这样做(虽然它的hacky和可怕):

$("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>
© www.soinside.com 2019 - 2024. All rights reserved.