fatma_wings
fatma_wings

Reputation: 113

Javascript: change id of elemnt

I have this elemnt:

<table id="listeCalOp"><tbody><tr><td><input name="calOp_date_debut_0" id="calOp_date_debut_0" value="" type="></tr></td></tbody></table>

I have change calOp_date_debut_0 to calOp_date_debut_22.

I try this code:

var markup = $('<tr>' + $('#listeCalOp').children('tbody:first').find('tr:first').clone().html().replace("calOp_date_debut_0",'calOp_date_debut_22') + '</tr>');

But it doesn't work.

Upvotes: 1

Views: 94

Answers (3)

distante
distante

Reputation: 7005

I don't know why you need jQuery to change the id of an element. This is vanilla javascript

var myElement = document.getElementById("calOp_date_debut_0");
myElement.id = "calOp_date_debut_12"
//if needed
myElement.name = "calOp_date_debut_12"

Do you need to clone your element too?

var myNewElement = myElement.cloneNode(false)

Do you need it with all the inner html (so children) ?

var myNewElement = myElement.cloneNode(true)

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68393

You can make couple of corrections

  • You can reach the element to clone via its id itself,
  • and no need for cloning when you are directly using its html.

i.e.

var markup = $('<tr>' + $('#calOp_date_debut_0').html().replace("calOp_date_debut_0",'calOp_date_debut_22') + '</tr>');

Or you can use clone for that element and then append that element to tr

var $newEl = $('#calOp_date_debut_0').clone();
$newEl.attr( "id", "calOp_date_debut_22" );
var markup = $("<tr></tr>").append( $newEl );

Upvotes: 0

treyBake
treyBake

Reputation: 6560

I see you're using jQuery: you can use the .attr function like so:

$('#my-id').attr('id', 'my-new-id')

ref: https://api.jquery.com/attr/

Upvotes: 2

Related Questions