如何选择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>
答案 0 :(得分: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>