From 9b1de35c3ed9e42ab9eebd27382cc0150885bb4c Mon Sep 17 00:00:00 2001 From: Krinkle Date: Wed, 13 Jul 2011 22:46:17 +0000 Subject: [PATCH] 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 --- resources/Resources.php | 3 +++ resources/jquery/jquery.getAttrs.js | 24 +++++++++++++++++++ tests/qunit/index.html | 2 ++ .../resources/jquery/jquery.getAttrs.js | 17 +++++++++++++ 4 files changed, 46 insertions(+) create mode 100644 resources/jquery/jquery.getAttrs.js create mode 100644 tests/qunit/suites/resources/jquery/jquery.getAttrs.js diff --git a/resources/Resources.php b/resources/Resources.php index 9bc4b8f0c5..4f01b7c61c 100644 --- a/resources/Resources.php +++ b/resources/Resources.php @@ -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', ), diff --git a/resources/jquery/jquery.getAttrs.js b/resources/jquery/jquery.getAttrs.js new file mode 100644 index 0000000000..c05012d97d --- /dev/null +++ b/resources/jquery/jquery.getAttrs.js @@ -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; +}; diff --git a/tests/qunit/index.html b/tests/qunit/index.html index 81fe7ecbd6..f0db23c295 100644 --- a/tests/qunit/index.html +++ b/tests/qunit/index.html @@ -43,6 +43,7 @@ + @@ -68,6 +69,7 @@ + diff --git a/tests/qunit/suites/resources/jquery/jquery.getAttrs.js b/tests/qunit/suites/resources/jquery/jquery.getAttrs.js new file mode 100644 index 0000000000..3d3d01e137 --- /dev/null +++ b/tests/qunit/suites/resources/jquery/jquery.getAttrs.js @@ -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 = $( '
', attrs ); + + deepEqual( $el.getAttrs(), attrs, 'getAttrs() return object should match the attributes set, no more, no less' ); +} ); -- 2.20.1