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?

6
  • $('div').attr('banana-20', $('div').attr('monkey-20')); $('div').removeAttr('monkey-20');? Commented Apr 8, 2014 at 22:56
  • 4
    I recommend using the html5 data attribute instead. eg <div data-banana-20="delicious" data-banana-100="delicious"></div> Commented Apr 8, 2014 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');}); Commented Apr 8, 2014 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. Commented Apr 9, 2014 at 0:51
  • Do you need to use Attributes or can you add Child elements like <div data-cat="monkey" data-num="20" data-val="delicious"/> to your div? Commented Apr 9, 2014 at 1:06

1 Answer 1

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);
    });
  });
};
Sign up to request clarification or add additional context in comments.

2 Comments

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: play.meyouand.us/140409-renameattr/rename-attr1.html
@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'); });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.