New jquery.getAttrs module

- A cross-browser compatible way of getting a direct key/value object of attributes
- Will help making comparisons such as in r92113 easier and work cross-browser
This commit is contained in:
Krinkle 2011-07-13 22:46:17 +00:00
parent a786ef815a
commit 9b1de35c3e
4 changed files with 46 additions and 0 deletions

View file

@ -114,6 +114,9 @@ return array(
'jquery.form' => array(
'scripts' => 'resources/jquery/jquery.form.js',
),
'jquery.getAttrs' => array(
'scripts' => 'resources/jquery/jquery.getAttrs.js',
),
'jquery.highlightText' => array(
'scripts' => 'resources/jquery/jquery.highlightText.js',
),

View file

@ -0,0 +1,24 @@
/**
* Utility to get all attributes of an element directy as an object.
*
* @author Timo Tijhof, 2011
*/
jQuery.fn.getAttrs = function( all ) {
var map = this[0].attributes,
attrs = {},
len = map.length,
i, v;
for ( i = 0; i < len; i++ ) {
// IE6 includes *all* allowed attributes for thew element (including those
// not set). Those have values like undefined, null, 0, false, "" or "inherit".
// However there may be genuine attributes set to that. If you need them,
// set all to true. They are excluded by default.
v = map[i].nodeValue;
if ( all || ( v && v !== 'inherit' ) ) {
attrs[ map[i].nodeName ] = v;
}
}
return attrs;
};

View file

@ -43,6 +43,7 @@
<script src="../../resources/jquery/jquery.byteLength.js"></script>
<script src="../../resources/jquery/jquery.byteLimit.js"></script>
<script src="../../resources/jquery/jquery.colorUtil.js"></script>
<script src="../../resources/jquery/jquery.getAttrs.js"></script>
<script src="../../resources/jquery/jquery.localize.js"></script>
<script src="../../resources/jquery/jquery.tabIndex.js"></script>
<script src="../../resources/jquery/jquery.tablesorter.js"></script>
@ -68,6 +69,7 @@
<script src="suites/resources/jquery/jquery.byteLength.js"></script>
<script src="suites/resources/jquery/jquery.byteLimit.js"></script>
<script src="suites/resources/jquery/jquery.colorUtil.js"></script>
<script src="suites/resources/jquery/jquery.getAttrs.js"></script>
<script src="suites/resources/jquery/jquery.localize.js"></script>
<script src="suites/resources/jquery/jquery.tabIndex.js"></script>
<script src="suites/resources/jquery/jquery.tablesorter.test.js" charset="UTF-8"></script>

View file

@ -0,0 +1,17 @@
module( 'jquery.getAttrs.js' );
test( '-- Initial check', function() {
expect(1);
ok( $.fn.getAttrs, 'jQuery.fn.getAttrs defined' );
} );
test( 'Check', function() {
expect(1);
var attrs = {
foo: 'bar',
'class': 'lorem'
},
$el = $( '<div>', attrs );
deepEqual( $el.getAttrs(), attrs, 'getAttrs() return object should match the attributes set, no more, no less' );
} );