views:

81

answers:

3

Does $(selector).attr(name) guarantee that the result is lowercase if the attribute is found?

+3  A: 

It will return the value in whatever case it was set.

<div class="sOmEcLaSs">content</div>

.

alert( $('div').attr('class')​​​​ );​​​​  // will alert sOmEcLaSs

If you want to convert to lowercase, you can use .toLowerCase().

alert( $('div').attr('class').toLowerCase() );​​​​  // will alert someclass

Code for jQuery's attr return statements (not Sizzle):

http://github.com/jquery/jquery/blob/1.4.2/src/attributes.js#L308

or

http://github.com/jquery/jquery/blob/1.4.2/src/attributes.js#L325

patrick dw
+2  A: 

No because .attr calls the javascript .getAttribute method without any parameters. As you can see in the code bellow.

getAttribute defaults to 0 which is a case-insensitive so it returns exactly what it finds.

     ATTR: function(elem, match){
            var name = match[1],
                result = Expr.attrHandle[ name ] ?
                    Expr.attrHandle[ name ]( elem ) :
                    elem[ name ] != null ?
                        elem[ name ] :
                        elem.getAttribute( name ),
                value = result + "",
                type = match[2],
                check = match[4];

            return result == null ?
                type === "!=" :
                type === "=" ?
                value === check :
                type === "*=" ?
                value.indexOf(check) >= 0 :
                type === "~=" ?
                (" " + value + " ").indexOf(check) >= 0 :
                !check ?
                value && result !== false :
                type === "!=" ?
                value !== check :
                type === "^=" ?
                value.indexOf(check) === 0 :
                type === "$=" ?
                value.substr(value.length - check.length) === check :
                type === "|=" ?
                value === check || value.substr(0, check.length + 1) === check + "-" :
                false;
        },
Mike
A: 

jQuery can't rely on case-sensitive attribute searches and still be cross-browser browser compatible. In the older IE DOM, I recall that all tags and attributes are stored and returned in upper case; so the tag <div id="mydiv"> gets rendered internally as <DIV ID=mydiv>. So in Netscape or Firefox, the attribute name would be id and in IE it would be ID. But even with dynamically created elements, which are stored with the desired case, there are inconsistencies just within IE. For example, IE6 and IE8 behave completely differently with getAttribute(). Compare:

<div></div>

var myDiv = document.getElementsByTagName('div')[0];
myDiv.setAttribute('id','id1');
myDiv.setAttribute('ID','id2');
console.log(x.getAttribute('ID')); // IE6, return "id1", IE8, returns "id2"
console.log(x.getAttribute('ID',true)); // IE6, return "id2", returns "id2"
Andrew