Frederic CS
Frederic CS

Reputation: 99

I cant change id a second time with jquery

I am trying to change the id of an element. It works the first time, but not the second time.

The HTML is:

<span id="1">trying to change the id after multiple clic</span>

The Jquery is:

jQuery( "#1").click(function() {
    $("#1").text("we change the id to 2");
    jQuery("#1").attr("id","2")
    console.log('id 1 clicked');
});


jQuery( "#2").click(function() {
    // it nevers goes there
    $("#2").text("we change the id to 3");
    jQuery("#2").attr("id","3")
    console.log('id 2 clicked');
});

here is the jsfiddle:

Thanks all for you help

Upvotes: 1

Views: 370

Answers (2)

Sarfraaz talat
Sarfraaz talat

Reputation: 635

You'll have to write your code which changes id from 2 to 3 inside the code that changes id from 1 to 2

Like this

jQuery( "#1").click(function() {
$("#1").text("we change the id to 2");
jQuery("#1").attr("id","2")
console.log('id 1 clicked');

jQuery( "#2").click(function() {
// it nevers goes there
$("#2").text("we change the id to 3");
jQuery("#2").attr("id","3")
console.log('id 2 clicked');

});

});

The reason being, that when you write the code outside it runs when the dom is initialized, and at that time, there is no element with id 2 , so the code is not affected

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370989

When you call .click on an element, the element that was just selected (here, #1 or #2) will get the listener attached to it. If the element doesn't exist when that line runs (like when you try to attach to #2), no listener will be attached.

For your situation, if you want to do something like this, you might use event delegation instead, so that the listeners are attached to the container:

$(document).on('click', "#1", function() {
  $("#1").text("we change the id to 2");
  $("#1").attr("id", "2")
  console.log('id 1 clicked');
});


$(document).on('click', "#2", function() {
  $("#2").text("we change the id to 3");
  $("#2").attr("id", "3")
  console.log('id 2 clicked');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="1">trying to change the id after multiple clic</span>

Another option is to save the current counter in a variable instead of in the DOM:

const $span = $('span');
const texts = {
  2: "click 2",
  3: "click 3"
};
let count = 1;
$span.on('click', () => {
  count++;
  console.log('click', count);
  $span.text(texts[count]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span>trying to change the id after multiple clic</span>

Upvotes: 2

Related Questions