Skip to content

Instantly share code, notes, and snippets.

@rwaldron
Created May 31, 2011 15:14
Show Gist options
  • Save rwaldron/1000671 to your computer and use it in GitHub Desktop.
Save rwaldron/1000671 to your computer and use it in GitHub Desktop.
A commonly requested feature that is simply not worth adding to jQuery core. Usage: http://jsfiddle.net/rwaldron/kSmP2/
/*!
* jQuery.fn.hasAttr()
*
* Copyright 2011, Rick Waldron
* Licensed under MIT license.
*
*/
(function( jQuery ) {
jQuery.fn.hasAttr = function( name ) {
for ( var i = 0, l = this.length; i < l; i++ ) {
if ( !!( this.attr( name ) !== undefined ) ) {
return true;
}
}
return false;
};
})( jQuery );
function assert( actual, expected, msg ) {
console.log(
( actual === expected && "PASS" ) || "FAIL: actual: " + actual + ", expected: " + expected,
msg
);
}
var $div = $("div");
assert( $div.hasAttr("class"), true, "class === 'foo'" );
assert( $div.hasAttr("title"), true, "title attr === 0" );
assert( $div.hasAttr("alt"), false, "alt attr === false" );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment