Scott B
Scott B

Reputation: 40157

Case insensitve comparison with jQuery?

In the "dev function" below, I'm trying to convert the string to lowercase to perform a lowercase to lowercase comparison between the string in the "html" variable and the contents of the span tags.

I must be doing something wrong on the dev function when attempting to convert the span to lowercase, since the highlight class does not appear to be attaching...

var html = jQuery('#content').html().toLowerCase();

    //existing function works when the span is preset to lowercase
    jQuery(".my_kw").find("span").filter(function() {
        return html.indexOf(jQuery(this).html()) != -1;
        }).each(function() {
            jQuery(this).addClass('highlight');
        });
    }

    //dev function. Trying to allow for spans to be mixed case, and force to lowercase only for comparison
    jQuery(".my_kw").find("span").filter(function() {
        var kw = jQuery(this).toLowerCase();
        return html.indexOf(kw.html()) != -1;
        }).each(function() {
            jQuery(this).addClass('highlight');
        });
    }

Upvotes: 1

Views: 8744

Answers (2)

Traveling Tech Guy
Traveling Tech Guy

Reputation: 27811

Seems to me like you call the .html() function (3rd line) after turning the span content to lower case (2nd line), thereby resulting in a mixed case string. Try this:

var kw = jQuery(this).html().toLowerCase();
return html.indexOf(kw) != -1;

Upvotes: 0

Andrew Song
Andrew Song

Reputation: 3128

I think you're missing a call to .html()

Consider your first call:

return html.indexOf(jQuery(this).html()) != -1;

and your second:

var kw = jQuery(this).toLowerCase();

That is, you probably want:

var kw = jQuery(this).html().toLowerCase();
return html.indexOf(kw) != -1;

Upvotes: 7

Related Questions