David Santamaria
David Santamaria

Reputation: 8811

Replacing jQuery ID

I am trying to replace the id of a jQuery element for the next one as follows: 'foo-1' --> 'foo-2'

And I finally ended with this:

$(this).attr('id',$(this).attr('id').replace(/-[0-9]*/,'-'+(parseInt($(this).attr('id').substring($(this).attr('id').indexOf('-')+1,$(this).attr('id').length))+1)));

Ugly, right? Any Ideas of how I would improve this.....?

Upvotes: 0

Views: 937

Answers (5)

steveyang
steveyang

Reputation: 9288

Use the replace callback function to simplify your code:

this.id = this.id.replace(/(-)(\d)*/, function ($1,$2,$3,$4) {
  console.log(arguments);
  var index = parseInt($3,10);
  return $2 + ++index + "";
});

$2 matches the first parentheses (which is '-' in your case), $3 matches the digitals. You then prase the digital with parseInt() and increment it by one. Finally, you put together the replaced string with + string operator.

Upvotes: 4

thecodeparadox
thecodeparadox

Reputation: 87073

$(this).attr('id',
function() {
    var me = this;
    return $(me).attr('id').replace(/[0-9]/g, '') + (parseInt($(me).index() + 1));
});

// this code snippet will assign id to element if it possess any id (like: foo-1/foo-2) or not

$(this).attr('id',
function() {
    var me = this;
    return ($(me).attr('id') ? $(me).attr('id').replace(/[0-9]/g, '') : 'foo-') + (parseInt($(me).index() + 1));
});

Upvotes: 1

Tadeck
Tadeck

Reputation: 137310

You can do it like that:

var el = jQuery(this);
var old_id = el.attr('id');
var id_number = parseInt(old_id.match(/\d/), 10);
el.attr('id', old_id.replace(id_number, id_number+1));

This has multiple advantages over your code:

  • it caches element you are processing (as el),
  • it caches processed ID of the element (as old_id),
  • it is very clean and readable,
  • it even uses less letters than your code,

See this jsfiddle for a proof of changing IDs into ones with higher integer in them.

Upvotes: 1

Adam Merrifield
Adam Merrifield

Reputation: 10407

var id = $(this).attr('id'),
    num = parseInt(id, 10),
    next = num + 1,
    string = id.substring(0, id.length - num.length) + next;


$(this).attr('id', string);

Upvotes: 2

Niels
Niels

Reputation: 49919

Maybe something like this

var num = parseInt( $(this).attr("id").replace(/[^0-9]+/g, ''));
var newid = id.replace(num, '') + (num + 1);

Live demo: http://jsfiddle.net/xH7Rf/

Upvotes: 1

Related Questions