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
  • 12
  • 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
  • 55,303
  • 33
  • 133
  • 164
2

Try

$('#carriage-promo').attr('id','carriage-promo-2');
Dipesh Parmar
  • 27,090
  • 8
  • 61
  • 90
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
  • 120,458
  • 37
  • 198
  • 307
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,811
  • 6
  • 30
  • 47