私の jQuery placeholder pluginでは、次を使用して、特定の要素のすべての属性を取得しています。
function args(elem) {
// Return an object of element attributes
var newAttrs = {},
rinlinejQuery = /^jQuery\d+$/;
$.each(elem.attributes, function(i, attr) {
if (attr.specified && !rinlinejQuery.test(attr.name)) {
newAttrs[attr.name] = attr.value;
}
});
return newAttrs;
}
elem
は要素オブジェクトであり、jQuery オブジェクトではないことに注意してください。
これを簡単に微調整して、data-*
属性名のみを取得できます。
function getDataAttributeNames(elem) {
var names = [],
rDataAttr = /^data-/;
$.each(elem.attributes, function(i, attr) {
if (attr.specified && rDataAttr.test(attr.name)) {
names.push(attr.name);
}
});
return names;
}
次に、結果の配列をループしてremoveAttr()
、要素の各アイテムを呼び出すことができます。
以下は、このトリックを実行する単純な jQuery プラグインです。
$.fn.removeAttrs = function(regex) {
return this.each(function() {
var $this = $(this),
names = [];
$.each(this.attributes, function(i, attr) {
if (attr.specified && regex.test(attr.name)) {
$this.removeAttr(attr.name);
}
});
});
};
// remove all data-* attributes
$('#my-element').removeAttrs(/^data-/);
// remove all data-lorem* attributes
$('#my-element').removeAttrs(/^data-lorem/);