简体   繁体   中英

How to select the element that has exactly the specified text

I'm not able to find anchor element by it's exact text content

HTML

<a href="javascript:void(0);">Project One</a>
<a href="javascript:void(0);">Project</a>

JS

var vInput = "Project";
alert($("a:contains('" + vInput + "')").length);

Output

2

I want the output to be 1 . Is there any way that I can match only the anchor element with the text Project NOT Project One ?

You can use filter() function and check if the text matches the desired string:

 alert($('a').filter(function() { return $(this).text() == 'Project'; }).length); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <a href="javascript:void(0);">Project One</a> <a href="javascript:void(0);">Project</a> 

You can use .filter() for matching the exact content as :contains() will return partial matches

 var vInput = "Project"; var $as = $('a').filter(function() { return vInput == $(this).text().trim() }) alert($as.length); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="javascript:void(0);">Project One</a> <a href="javascript:void(0);">Project</a> 

USe filter

var vInput = "Project";
var anchors = $("a").filter(function() {
    return $(this).text().trim() == vInput;
});
alert(anchors.length);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM