2

using jQuery I would like to change the ID one of element within a page, a div, and give it a new one. I cannot use classes, must be ID. This will be part of an IF statement, for example: (pseudo:)

if x = greater than 1, change id of x to y else do nothing

So far I have:

$('#carriage-promo').attr('id','#carriage-promo-2');

However, this doesn't seem to work. Any suggestions?

I've never worked with ID, always class, and I would have used addClass and removeClass, which have always worked for me in the past!

Myles
  • 926
  • 2
  • 9
  • 29

4 Answers4

6
$('#carriage-promo').attr('id','#carriage-promo-2');

No need of #. So remove it

$('#carriage-promo').attr('id','carriage-promo-2');

or you can use .prop()

$('#carriage-promo').prop('id','carriage-promo-2');

See the perform test case in jsperf

Here is a sample Fiddle

Community
  • 1
  • 1
Praveen
  • 53,079
  • 32
  • 129
  • 156
2

Try

$('#carriage-promo').attr('id','carriage-promo-2');
Dipesh Parmar
  • 26,601
  • 7
  • 57
  • 86
1

Just apply the String you want to update.

$('#carriage-promo').attr('id','carriage-promo-2');

Why because '#' is to select the element, with perticular Id

ID is DOM specific and # is Jquery specific.

Suresh Atta
  • 118,038
  • 37
  • 189
  • 297
1

No need of #, just use the id:

$('#carriage-promo').attr('id','carriage-promo-2');

Better use prop(). There have been some changes with attr() and prop() from Jquery v1.6 onwards:

$('#carriage-promo').prop('id','carriage-promo-2');

prop() is for Properties and attr() is for Attributes.

Vivek Jain
  • 3,733
  • 6
  • 28
  • 46