1

The title looks a little confusing, so let me show an example:

Markup

<div id="MyDiv"></div>
<div id="SecondaryDiv"></div>

JS

// Set the HTML5 data key 'name' to value 'MyName'
$("#MyDiv").data("name", "MyName");

// Return all divs with the data key 'name' matching 'MyName'
//     This works without a hitch
$("div").filter(function () {
    return $(this).data("name") === "MyName";
});

// This breaks because I try to add '.toLowerCase()' to the end of the .data() function.
// The error returned is:
//     TypeError: $(...).data(...) is undefined
$("div").filter(function () {
    return $(this).data("name").toLowerCase() === "myname";
});

How can I ignore case when comparing $(...).data(...) values?

As a side note, even if I do this:

// This throw an error saying:
//     TypeError: val is undefined
var val = "";
$("div").filter(function() {
    val = $(this).data("name");
    return val.toLowerCase() === "myname";
});
BenR
  • 2,791
  • 3
  • 26
  • 36
  • try using "$("#MyDiv").data" instead of "$(this).data" – Marvin Smit May 05 '14 at 20:52
  • @MarvinSmit notice that it is in a `filter` function. I can't use `$("#MyDiv")` because I want to compare against every element in the initial selector. Not only against only `MyDiv`. – BenR May 05 '14 at 20:53
  • 1
    So are you setting the '.data' property of those div's anywhere? if not $(this).data("name") will return 'undefined'. on which you cannot call .toLowerCase(). – Marvin Smit May 05 '14 at 20:56
  • @MarvinSmit As you see in the example I am setting it in the second line of the JS code. – BenR May 05 '14 at 20:57
  • That's only on the element with "MyDiv" as id. – Marvin Smit May 05 '14 at 20:58

1 Answers1

2

you can't run .toLowerCase() on undefined, so test if the return value for .data('name') is undefined first:

$("div").filter(function () {
    if ($(this).data("name")) {
        return $(this).data("name").toLowerCase() === "myname";
    } else {
        return false;
    };
});

http://jsfiddle.net/mblase75/yX4X2/

or more succinctly:

$("div").filter(function () {
    return $(this).data("name") && ($(this).data("name").toLowerCase()==="myname");
});

http://jsfiddle.net/mblase75/yX4X2/1/


(However, be aware that $(this).data("name") can potentially return "falsey" values like false or 0, since .data() attempts to convert strings to their appropriate type. See this question.)

Community
  • 1
  • 1
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
  • Ooh that makes total sense! Thank you! As it's enumerating through each item, some will not have that data attribute, so calling a function on it will throw an error. It's so obvious after it makes sense, lol. – BenR May 05 '14 at 21:03