Reputation: 11623
I have the following code:
<div id="elm0" data-color="color" data-size="size" data-more="more">something</div>
<div id="elm1">This element must get elem0 attr</div>
I know that I can get $("#elm0").attr("color") in a var and pass it to $("#elm1") but in my case I do not know exactly what attributes are there. I am looking for something that does:
get all attr from $("#elm0") and pass them to $("#elm1")
How can I do this? Thanx
Edit: I need to get only HTML5 data attributes like data-color="color", data-size="size" not class, ID, style...
Upvotes: 0
Views: 750
Reputation: 630469
You could do something like this in vanilla JavaScript:
var elm0a = document.getElementById("elm0").attributes,
elm1 = document.getElementById("elm1");
for(var i=0; i<elm0a.length; i++) {
var a = elm0a[i];
if(a.name.indexOf("data-") == 0)
elm1.setAttribute(a.name, a.value);
}
You can give it a try here, or...in plugin form!
jQuery.fn.copyDataAttrTo = function(selector) {
var a = this[0].attributes, attrMap = {};
for(var i=0; i<a.length; i++) {
if(a[i].name.indexOf("data-") == 0) attrMap[a[i].name] = a[i].value;
}
$(selector).attr(attrMap);
return this;
};
You would call it like this:
$("#elm0").copyDataAttrTo("#elm1");
You can test that version here.
Upvotes: 1
Reputation: 75317
jQuery.fn.getDataMap = function () {
var map = {};
if (!this.length) {
return map;
}
var attributes = this[0].attributes;
for (var i=0;i<attributes.length;i++) {
var curr = attributes[i];
if (curr.nodeName.indexOf("data-") === 0) {
map[curr.nodeName] = curr.nodeValue;
}
}
return map;
}
Then use it as follows:
$('#elm1').attr($('#elm0').getDataMap());
http://www.jsfiddle.net/Ag5Dv/
Upvotes: 1
Reputation: 236032
This should do it. You could easily do it without jQuery aswell.
$(function(){
var src = $('#elm0'),
dst = $('#elm1'),
attr = src[0].attributes;
for(var i = 0, len = attr.length; i < len; i++){
var current = attr[i];
dst.attr(current[i].nodeName, current[i].nodeValue);
}
});
http://www.jsfiddle.net/pnCdK/
Upvotes: 1