5

I have a .jsp page where many elements have ids that end with a certain string. For example:

<div id="topActions-1083"></div>
<div id="collapse-1083">
<input id="collapse1Input-1083" type="hidden" value="expanded"></input>
</div>

Which is the fastest way to get all elements with id ending in '1083' and change it to '1084' ?

Pramod S. Nikam
  • 4,271
  • 4
  • 38
  • 62
Theodore K.
  • 5,058
  • 4
  • 30
  • 46
  • In first place, do you really need to use IDs? – A. Wolff Jun 19 '14 at 11:59
  • Read [How can I select an element by ID with jQuery using regex?](http://stackoverflow.com/questions/13541898/how-can-i-select-an-element-by-id-with-jquery-using-regex) – Braj Jun 19 '14 at 12:00

3 Answers3

4

Try this

$("[id*=1083]").each(function(){
   var iid = $(this).attr('id')
   var fin = iid.replace('1083','1084')
   $(this).attr('id',fin)
   console.log(fin)
});

Working DEMO

Selectors Example :

Starts with a given string (for example 1083),

$("[id^='1083']")

If you want to select elements which id contains a given string :

$("[id*='1083']")

If you want to select elements which id is not a given string :

$("[id!='1083']")
Sridhar R
  • 20,190
  • 6
  • 38
  • 35
3

Try to use the .attr()'s receiver function,

$('[id$=1083]').attr('id',function(_,id){ 
    return id.substr(id.length - 4) + '1084'; 
});

DEMO

Or as wolf suggested you could use .split() instead of .substring()

$('[id$=1083]').attr("id", function (_, id) {   
   return id.split('-')[0] + '-1084';
});
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
1

You may possibly try this:

script

$(function()
{
    $('[id$=1083]').prop('id',function()
    {
        return this.id.replace('1083', '1084');
    });
});