选择第一个标签但不选择第二个

时间:2016-02-21 17:38:03

标签: jquery

我有这个HTML:

<div class="content">
    <p>testing</p>
    <h4>Title</h4>
    <p>still testing</p>
    <h4>Another title</h4>
</div>
<div class="content">
    <p>testing</p>
    <h4>Title</h4>
    <p>still testing</p>
    <h4>Another title</h4>
</div>
<div class="content">
    <p>testing</p>
    <h4>Title</h4>
    <p>still testing</p>
    <h4>Another title</h4>
</div>

我想只选择所有<h4>类中的第一个content标记。到目前为止,我有:

$('.content h4').each(function(i, element){
    var test = $(this).text();
    console.log(test);
}

但这会给我所有h4个标签。我怎么能只针对第一批呢?

注意:HTML是简化版本,因此无法保证h4始终是内容中的第二个和第四个标记。

3 个答案:

答案 0 :(得分:1)

$(".content").each(function() {
  $(this).find("h4").eq(0);
});

查看CODEPEN

中的工作示例

答案 1 :(得分:1)

使用:first-of-type,如下所示。

$('.content h4:first-of-type').each(function (i, element) {
    var test = $(this).text();
    console.log(test);
});

实例:

&#13;
&#13;
var matches = $(".content h4:first-of-type");
matches.css("color", "green");
&#13;
<div class="content">
    <p>testing</p>
    <h4>Title</h4>
    <p>still testing</p>
    <h4>Another title</h4>
</div>
<div class="content">
    <p>No H4 in this one, as an example</p>
    <p>still testing</p>
</div>
<div class="content">
    <p>testing</p>
    <h4>Title</h4>
    <p>still testing</p>
    <h4>Another title</h4>
</div>
<div class="content">
    <p>testing</p>
    <h4>Title</h4>
    <p>still testing</p>
    <h4>Another title</h4>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

没有一个选择器能够做到这一点 (现在针对这种特殊情况,在CSS3中;请参阅Azim's answer;对于,以下情况仍然如此一般不是特定于简单标签的情况),你需要一个循环,例如:

var matches = $(".content").map(function() {
    return $(this).find("h4")[0];
});

这是通过从循环遍历.content元素并返回其第一个h4元素的结果构建新的jQuery对象来实现的。 (如果它们没有h4,则回调将返回undefined,并且jQuery会将其从结果中删除。)

实例:

var matches = $(".content").map(function() {
  return $(this).find("h4")[0];
});
matches.css("color", "green");
<div class="content">
    <p>testing</p>
    <h4>Title</h4>
    <p>still testing</p>
    <h4>Another title</h4>
</div>
<div class="content">
    <p>No H4 in this one, as an example</p>
    <p>still testing</p>
</div>
<div class="content">
    <p>testing</p>
    <h4>Title</h4>
    <p>still testing</p>
    <h4>Another title</h4>
</div>
<div class="content">
    <p>testing</p>
    <h4>Title</h4>
    <p>still testing</p>
    <h4>Another title</h4>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

相关问题