我可以通过jQuery在一组兄弟姐妹中选择多个“第一类型”吗?

时间:2019-12-11 04:55:30

标签: jquery

在此示例中,是否可以使用jQuery / js在兄弟姐妹(即a,d和i)中选择每组“ .two” div中的第一个?

<div>
    <div class='two'>a</div>
    <div class='one'>b</div>
    <div class='one'>c</div>
    <div class='two'>d</div>
    <div class='two'>e</div>
    <div class='two'>f</div>
    <div class='one'>g</div>
    <div class='one'>h</div>
    <div class='two'>i</div>
    <div class='two'>j</div>
</div>

3 个答案:

答案 0 :(得分:6)

使用not()

$('.two:first-child, :not(.two) + .two').each(function() {
  console.log(this.textContent);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>
  <div class='two'>a</div>
  <div class='one'>b</div>
  <div class='one'>c</div>
  <div class='two'>d</div>
  <div class='two'>e</div>
  <div class='two'>f</div>
  <div class='one'>g</div>
  <div class='one'>h</div>
  <div class='two'>i</div>
  <div class='two'>j</div>
</div>

答案 1 :(得分:2)

一种选择是组合选择器.two:first-child.one + .two

$('.two:first-child, .one + .two').each(function() {
  console.log(this.textContent);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
    <div class='two'>a</div>
    <div class='one'>b</div>
    <div class='one'>c</div>
    <div class='two'>d</div>
    <div class='two'>e</div>
    <div class='two'>f</div>
    <div class='one'>g</div>
    <div class='one'>h</div>
    <div class='two'>i</div>
    <div class='two'>j</div>
</div>

(还要注意,您可能希望将每行末尾的<div>更改为</div>-您想 end div,而不是重新开始div,在一行的末尾)

答案 2 :(得分:0)

:first-of-type选择器将匹配没有其他元素且元素父和名字都在文档树中的元素。 在每个匹配的div中找到第一个跨度,然后向其添加一个类。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>first-of-type demo</title>
  <style>
  span.fot {
    color: red;
    font-size: 120%;
    font-style: italic;
  }
  </style>
  <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>
<body>
 
<div>
  <span>Text1,</span>
  <span>Text2,</span>
  <span>Text3,</span>
  <span>Text4</span>
</div>
<div>
  <b>Demo1,</b>
  <span>Demo2,</span>
  <span>Demo3,</span>
  <span>Demo4</span>
</div>
 
<script>
$( "span:first-of-type" ).addClass( "fot" );
</script>
 
</body>
</html>