We could also try extending the jQuery prototype ($.fn
) object to provide a new method that can be chained to the jQuery() function.
Here's an extension of @pimvdb's solution to provide a function that copies all attributes
The usage would be like so:
$(destinationElement).copyAllAttributes(sourceElement);
The extension function can be defined like so:
(function ($) {
// Define the function here
$.fn.copyAllAttributes = function(sourceElement) {
// 'that' contains a pointer to the destination element
var that = this;
// Place holder for all attributes
var allAttributes = ($(sourceElement) && $(sourceElement).length > 0) ?
$(sourceElement).prop("attributes") : null;
// Iterate through attributes and add
if (allAttributes && $(that) && $(that).length == 1) {
$.each(allAttributes, function() {
// Ensure that class names are not copied but rather added
if (this.name == "class") {
$(that).addClass(this.value);
} else {
that.attr(this.name, this.value);
}
});
}
return that;
};
})(jQuery);
An Example is available at http://jsfiddle.net/roeburg/Z8x8x/
Hope this helps.
id
? – Nimrodid
attribute you will have a duplicatedid
. – Kacykaczer