1

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

Udo E.
  • 1,958
  • 1
  • 13
  • 24
  • [What are valid values for the id attribute in HTML?](https://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html) – Pedram Jan 25 '20 at 06:58

2 Answers2

2

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>
CertainPerformance
  • 260,466
  • 31
  • 181
  • 209
0

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

sarfraaz talat
  • 555
  • 3
  • 9