Add setDOMAttributes()

Change-Id: I1406998400c4f7f3d0983a43e3f86afe4ffd29a6
This commit is contained in:
Catrope 2012-10-03 17:48:06 -07:00
parent ac4c259a19
commit 3f4c656275
2 changed files with 40 additions and 0 deletions

View file

@ -262,3 +262,27 @@ QUnit.test( 'copyObject', 6, function ( assert ) {
'Object with sparse array'
);
} );
QUnit.test( 'getDOMAttributes', 1, function ( assert ) {
assert.deepEqual(
ve.getDOMAttributes( $( '<div foo="bar" baz quux=3></div>').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'
);
} );

View file

@ -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;
}() );