4

How can I change

<div data-300=""></div>

to

<div data-500=""></div>

using jquery?

I don't want to remove the attribute and replace it as it contains data I need I just need to change the '300' to '500'.

2
  • 3
    You will need to replace it, but that doesn't mean you need to lose the value. Commented Sep 11, 2013 at 21:21
  • possible duplicate of stackoverflow.com/questions/317170/… Commented Sep 11, 2013 at 21:53

2 Answers 2

4

Not generic at all, but it should do the job

var $target = $('div[data-300]'),
    oldData = $target.data('300');

$target.removeAttr('data-300').attr({ 'data-500': oldData });
Sign up to request clarification or add additional context in comments.

1 Comment

Legend! Thanks for the speedy answer!
3

Here's a function you can use:

function attrChangeName(elem, attr, new_attr) {
  var data = $(elem).attr(attr);
  $(elem).attr(new_attr, data);
  $(elem).removeAttr(attr);
}

3 Comments

That simplifies things a lot. Thanks! In the interest of making the code easier to read (it would just make more sence to me when reading through code) would it be possible to make it so the call could be something like this: $('element').attrChangeName(attr, new_attr);
Sure, you can create a jQeury plugin. Look at this link learn.jquery.com/plugins/advanced-plugin-concepts. It is pretty straight forward. If you go this route, it will be easy to rename the attrs for entire collections, the way other jQuery functions work.
Sorry I was meant to be doing this, but ran out of time. So I just went with your above method which works perfectly anyway... Why change a good thing? :)

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.