Select元素使用jQuery有两个特定的子元素

时间:2019-03-19 05:43:38

标签: javascript jquery html jquery-selectors

我想通过匹配两个孩子来选择父对象。 我的代码:

$('span:contains("11:00am"), span.name:contains("Tom")').parents("a").css("background-color","rgb(255, 255, 255)");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a style="background-color: rgb(0, 0, 0);">
  <div class="time">
    <span>11:00am</span>
  </div>
  <span class="name">Tom</span>
</a>
<a style="background-color: rgb(0, 0, 0);">
  <div class="time">
    <span>11:00am</span>
  </div>
  <span class="name">Jack</span>
</a>

但是,这将同时选择 Tom Jack 的时间。

2 个答案:

答案 0 :(得分:2)

您需要选择a标签,然后使用:has()选择器来过滤具有特定子元素的元素。

$('a:has(span:contains("11:00am")):has(span.name:contains("Tom"))')

$('a:has(span:contains("11:00am")):has(span.name:contains("Tom"))').css("background-color","rgb(255, 255, 255)");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a style="background-color: rgb(0, 0, 0);">
  <div class="time">
    <span>11:00am</span>
  </div>
  <span class="name">Tom</span>
</a>
<a style="background-color: rgb(0, 0, 0);">
  <div class="time">
    <span>11:00am</span>
  </div>
  <span class="name">Jack</span>
</a>

答案 1 :(得分:0)

$('span:contains("11:00am"),span:contains("Jack")').parent("a").css("background-color", "Grey");
$('span:contains("11:00am"),span:contains("Tom")').parent("a").css("background-color", "Green");
<a style="background-color: rgb(255, 255, 255);">
  <div class="time">
    <span>11:00am</span>
  </div>
  <span class="name">Tom</span>
</a>

<a style="background-color: rgb(255, 255, 255);">
  <div class="time">
    <span>11:00am</span>
  </div>
  <span class="name">Jack</span>
</a>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>