Changing id with attr doesn't change it's behavior only styles

Hi,

I use attr to change id of my element:

$('#id1').attr('id','ids1');

I use different CSS styles for id1 and ids1, and I see that styles of the element change to ids1. However, I also have some behavior attached to id1 and ids1.

$("#id1").click(function(){
  alert("I am id1")
});

$("#ids1").click(function(){
  alert("I am ids1")
});

This behavior doesn’t change for some reason. I still receive id1 alert on click.

Keep in mind that event binding is something that’s only done when the binding function is called, not when the event fires. When you call click on a jQuery selection,
you’re attaching the event handler, and then the code doesn’t get run again. The event handler will execute every time the event hits that element, but the binding is
a separate operation.

// this only gets run once
$("#id1").click(function(){
  alert("I am id1")
});

$('someElement').attr('id', 'id1'); // no event has been bound to this yet. Re-run the binding:

$("#id1").click(function(){
  alert("I am id1")
});

A better way to handle this is with event delegation, which jQuery makes very easy to do:

$('div.someGeneralClassOfElements').click('#id1', function() {
    //this will only run on an element that has a class of "someGeneralClassOfElements" AND the id "id1"
})
1 Like
    <script>
        $(function(){
                       

            var ids1click = function(){
                alert("I am ids1")
            };

            var id1click = function(){
                alert("I am id1")
            };

            $('#id1').bind("click", id1click); 

            $('#id1').unbind("click").attr('id','ids1').bind("click",ids1click);
        })
    </script>

in this example when I comment $('#id1').unbind("click").attr('id','ids1').bind("click",ids1click); I see "I’m id1’ and when let it as it is I see “I’m ids1”.

so you should first unbind the callback attached because changing the id will not bind to it the callback you want

1 Like