如何将第一个元素与确切内容匹配?

我有四个锚元素,其内容分别为“ taw”,“ wat”,“ wat 2”和“ wat”。是否可以选择仅包含“ wat”的第一个元素?

到目前为止,我已经拥有了:

$("a").filter(function() {
    return $(this).text() === "wat";
}).css("font-weight","bold");

它正在选择第二个和最后一个元素。我只希望选择包含“ wat”的第一个元素。谢谢!

演示:https://codepen.io/obliviga/pen/jOOZeGZ?editors=1010

zq4352684 回答:如何将第一个元素与确切内容匹配?

使用.first()

$("a").filter(function() {
    return $(this).text() === "wat";
}).first().css("font-weight","bold");
,

您可以使用.first() 将匹配元素的集合减少到集合中的第一个

$(".myDiv").filter(function() {
    return $(this).text() === "wat";
}).first().css("font-weight","bold");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="myDiv">taw</div>
<div class="myDiv">wat</div>
<div class="myDiv">wat 2</div>
<div class="myDiv">wat</div>

本文链接:https://www.f2er.com/3163171.html

大家都在问