How to copy all the attributes of one element and apply them to another?
You can use the native Node#attributes
property: http://jsfiddle.net/SDWHN/16/.
var $select = $("select");
var $div = $("div");
var attributes = $select.prop("attributes");
// loop through <select> attributes and apply them on <div>
$.each(attributes, function() {
$div.attr(this.name, this.value);
});
alert($div.data("foo"));
Pretty Simple
function cloneAttributes(element, sourceNode) {
let attr;
let attributes = Array.prototype.slice.call(sourceNode.attributes);
while(attr = attributes.pop()) {
element.setAttribute(attr.nodeName, attr.nodeValue);
}
}
ES6 syntax one liner:
function cloneAttributes(target, source) {
[...source.attributes].forEach( attr => { target.setAttribute(attr.nodeName ,attr.nodeValue) })
}
And as noted in the first comment - you would probably don't want to copy the source id attribute... so this one will save it as a 'data-id' attribute in case you need a reference.
function cloneAttributes(target, source) {
[...source.attributes].forEach( attr => { target.setAttribute(attr.nodeName === "id" ? 'data-id' : attr.nodeName ,attr.nodeValue) })
}