0

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?

Marc P
  • 606
  • 1
  • 11
  • 26
  • `$('div').attr('banana-20', $('div').attr('monkey-20')); $('div').removeAttr('monkey-20');`? – putvande Apr 08 '14 at 22:56
  • 4
    I recommend using the html5 `data` attribute instead. eg
    – John Apr 08 '14 at 22:56
  • @putvande methods can be chained to avoid useless dom traversal .. `var $div = $('div'); $div.each(function(){var t = $(this); t.attr('banana-20', (t.attr('monkey-20') || '')).removeAttr('monkey-20');});` – Stphane Apr 08 '14 at 23:03
  • I should have mentioned: there are going to be cases where there are multiple attributes with varying numbers. I want to change all attribute names starting with "monkey" and change them to "banana", but leave the dashes and numbers unchanged. – Marc P Apr 09 '14 at 00:51
  • Do you need to use Attributes or can you add Child elements like `
    ` to your div?
    – collapsar Apr 09 '14 at 01:06
  • Unfortunately, I need the category and the number attached to each other. – Marc P Apr 09 '14 at 01:54

1 Answers1

1

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);
    });
  });
};
WynandB
  • 1,377
  • 15
  • 16
  • Your argument is totally valid: unfortunately, the project is very specific, so your solution may actually be perfect for its requirements! I've added the function but am I calling it correctly in this example: http://play.meyouand.us/140409-renameattr/rename-attr1.html – Marc P Apr 09 '14 at 20:47
  • @MarcP Yes you are, but in that example you'll need to call the plug-in function on DOM ready, e.g. `$(function() { $('div').renameAttrs('monkey', 'banana'); })`; – WynandB Apr 09 '14 at 22:32