Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 
like image 202
Andrew Avatar asked Jul 19 '11 20:07

Andrew


People also ask

Can an element have multiple data attributes?

A data attribute is a custom attribute that stores information. Data attributes always start with “data-” then followed with a descriptive name of the data that is being stored. You can have multiple data attributes on an element and be used on any HTML element.


2 Answers

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")); 
like image 110
pimvdb Avatar answered Oct 13 '22 17:10

pimvdb


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) }) } 
like image 27
Yair Levy Avatar answered Oct 13 '22 17:10

Yair Levy