Reputation: 586
I want to change attribute names with variables. However, I can't wrap my head around how to access just the constant. In the following example, I want to change all attribute names starting with "monkey" and change them to "banana", but leave the dashes and numbers unchanged.
Change the following:
<div monkey-20="delicious" monkey-100="delicious">
To this:
<div banana-20="delicious" banana-100="delicious">
Anyone have tips?
Upvotes: 0
Views: 313
Reputation: 1427
I could argue that your specific requirement to change attribute names is somewhat unusual, so a somewhat unorthodox solution in the form of a jQuery plug-in might work for you:
$.fn.renameAttrs = function() {
var oldName = arguments[0] + '-',
newName = arguments[1] + '-';
return this.each(function() {
var $node = $(this),
attrs = [];
$.each(this.attributes, function() {
var index = this.name.indexOf(oldName);
if (!index) {
$node.attr(newName + this.name.substr(oldName.length), this.value);
attrs.push(this);
}
});
$.each(attrs, function() {
$node.removeAttr(this.name);
});
});
};
Upvotes: 1