Rob
Rob

Reputation: 63

Using JQuery to change element ID

I've been trying to change an element ID using jquery for an A/B test.

From what ive seen, it should go something like this:

$('#tag').attr('oldId','newId');

But so far, no dice - any ideas?

*I've looked through the responses and i think i had the wrong end of the stick! I was assuming the current / old id had to be placed where ive labelled 'oldId', rather than id, followed by the replacement - silly mistake, thanks for all the help :)

Upvotes: 3

Views: 12803

Answers (8)

Rob
Rob

Reputation: 63

Thanks guy, ended up using:

$('#tag').attr("id","newId")

with 'id' as 'id' and not current id tag

Upvotes: 0

rkatkam
rkatkam

Reputation: 2804

$("#tag"), here "tag" is your id. line2: $("#tag").attr("id","newId"); You should not pass "tag" as your first param to attr. You must tell which attribute you want to set, i.e "id", followed by a value. In a simpler language, line2 attr function takes a key and its value to be set.

Upvotes: 0

Gaurav Barthwal
Gaurav Barthwal

Reputation: 21

Use this: $('#oldID').attr('id','newID');
you have to pass attrbuteName as first argument and attributeValue as second argument.

Upvotes: 0

Alnitak
Alnitak

Reputation: 340055

If oldId really is the element's current ID, then instead of #tag you just need:

$('#oldId').attr('id', 'newId');

Upvotes: 0

naoxink
naoxink

Reputation: 597

Edited The right syntax is: $("#myId").attr("id", "mySecondId")

Upvotes: 1

pas
pas

Reputation: 98

Try this:

$('#tag').attr('id','newId');

Upvotes: 0

Manoj
Manoj

Reputation: 5071

Try this

$('#tag').attr('id','newId');

This will change id of element

Working Demo

Upvotes: 0

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

Try to use the proper signature of .attr('attributeName','value'),

$('#tag').attr("id","newId")

Upvotes: 13

Related Questions