1

I have a link inside of a div element. The link has a click listener.

$(document).ready(function() {
    $('#theLink').click(function() {
        // do stuff
    });
})

<div id="myElement"><a class="myLink" id="theLink">Click here</a></div>

At some point in my application, I have to clear the div elements contents, and then have to re-write them again later. When I rewrite the link using .html(''), I lose the click listener and the link doesn't work.

$('#myElement').html(''); // clear element

$('#myElement').html('<a class="myLink" id="theLink">Click here</a>');

Do I need to add a new listener to get this link working again?

7
  • 4
    Use .live() or .on() instead of .click() Commented Jan 22, 2012 at 16:07
  • 1
    @ShadowWizard this isn't a comment, because it's the answer :) Commented Jan 22, 2012 at 16:14
  • Why must you destroy the element? Why not just hide/show it? It doesn't make sense to continuously destroy and recreate the same element, even if methods like on() or live() let you. Commented Jan 22, 2012 at 16:21
  • +1 @ShadowWizard. I tried using .on() without any success but .live() worked perfectly, thanks. Commented Jan 22, 2012 at 16:35
  • 1
    Cheers @Ahmet and Martin.. feel free to accept SKS answer it's exactly my intention plus great demo. Commented Jan 22, 2012 at 22:06

3 Answers 3

1

You can use .on and specify the container of the link to have it listen after being removed and added again.

Edit: You can read about below approach in their documentation. See under section Direct and delegated events.

See DEMO here

Something like below should work,

$('#myElement').on('click', '#theLink', function() {
  alert('HI!');
});

I think internally jQuery does something like below,

$('#myElement').click (function (e) {
    if (this.id == 'theLink') {
       alert('Hi!');
       e.stopPropogation();           
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

You should probably use jQuery's on() function (jQuery 1.7+). This will allow you to bind the click event to your element regardless of how many times you add and remove it.

For example:

$("#theLink").on("click", function(event){
    //do stuff;
});

Update: For jQuery versions earlier than 1.7 use either bind() or live() (depending on the exact jQuery version). The same syntax applies.

Comments

0

I think that

$('#myElement').children('id!="myLink"').remove()

Should remove all children of the container div other than the link. However, I'm not sure if the selector expression inside children() is correctly formatted, so it might cause a syntax error. If so, please comment and I'll edit the answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.