views:

25

answers:

3

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...

+1  A: 

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/

jAndy
+1  A: 

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.

Nick Craver
Great! this works.
Mircea
+1  A: 
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/

Matt
Thanx Matt, it works!
Mircea