Search code examples
jqueryselectorcontain

span:contains() finds to many numbers


This code:

if( $('span:contains("'+user_choice+'")').length == 0 )

uses the contain selector to find the <span>, which contains the user input. The user input user_choice is a number, like 1 or 23 or 31 etc.

But the code fails to find the specific <span>, since e.g. the user input user_choice = 1 will find both 1 and 21 and 31 and all numbers that contain 1. I need only to find the specific <span> that is exactly 1.

Is the contain selector wrong for this purpose and how can I correct it to make it work?


Solution

  • Yes, the contains selector is wrong for your purpose. As the name suggests it matches any element that contains the specified text as a substring, not only those elements where there's an exact match.

    You could try using .filter():

    var matchingElements = $('span').filter(function(index) {
        return $(this).text() === user_choice;
    });
    if(matchingElements.length === 0) {
        ...
    }