简体   繁体   中英

change data-attribute using jquery

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'.

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 });

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM