From 3f4c656275c41721cae23d90bb5443bb1725afff Mon Sep 17 00:00:00 2001 From: Catrope Date: Wed, 3 Oct 2012 17:48:06 -0700 Subject: [PATCH] Add setDOMAttributes() Change-Id: I1406998400c4f7f3d0983a43e3f86afe4ffd29a6 --- modules/ve/test/ve.test.js | 24 ++++++++++++++++++++++++ modules/ve/ve.js | 16 ++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/modules/ve/test/ve.test.js b/modules/ve/test/ve.test.js index 0f3430b2f0..2ba299c6f3 100644 --- a/modules/ve/test/ve.test.js +++ b/modules/ve/test/ve.test.js @@ -262,3 +262,27 @@ QUnit.test( 'copyObject', 6, function ( assert ) { 'Object with sparse array' ); } ); + +QUnit.test( 'getDOMAttributes', 1, function ( assert ) { + assert.deepEqual( + ve.getDOMAttributes( $( '
').get( 0 ) ), + { 'foo': 'bar', 'baz': '', 'quux': '3' }, + 'getDOMAttributes() returns object with correct attributes' + ); +} ); + +QUnit.test( 'setDOMAttributes', 2, function ( assert ) { + var element = document.createElement( 'div' ); + ve.setDOMAttributes( element, { 'foo': 'bar', 'baz': '', 'quux': 3 } ); + assert.deepEqual( + ve.getDOMAttributes( element ), + { 'foo': 'bar', 'baz': '', 'quux': '3' }, + 'setDOMAttributes() sets attributes correctly' + ); + ve.setDOMAttributes( element, { 'foo': null, 'bar': 1, 'baz': undefined, 'quux': 5, 'whee': 'yay' } ); + assert.deepEqual( + ve.getDOMAttributes( element ), + { 'bar': '1', 'quux': '5', 'whee': 'yay' }, + 'setDOMAttributes() overwrites attributes, removes attributes, and sets new attributes' + ); +} ); diff --git a/modules/ve/ve.js b/modules/ve/ve.js index 4db486299b..319e55bcb8 100644 --- a/modules/ve/ve.js +++ b/modules/ve/ve.js @@ -644,6 +644,22 @@ return result; }; + /** + * Set the attributes of a DOM element as an object with key/value pairs + * @param {HTMLElement} element + * @param {Object} attributes + */ + ve.setDOMAttributes = function ( element, attributes ) { + var key; + for ( key in attributes ) { + if ( attributes[key] === undefined || attributes[key] === null ) { + element.removeAttribute( key ); + } else { + element.setAttribute( key, attributes[key] ); + } + } + }; + // Expose window.ve = ve; }() );