How to copy all the attributes of one element and apply them to another?

javascript, jquery

Solution

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"));

Problem

How do I copy the attributes of one element to another element? HTML ``` <select id="foo" class="bar baz" style="display:block" width="100" data-foo="bar">...</select> <div>No attributes yet</div> ``` JavaScript ``` var $div = $('div'); var $select = $('select'); //now copy the attributes from $select to $div ```

Original source