Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically added HTML elements can't be found using jQuery

Tags:

html

jquery

I am implementing a tree browser in HTML. On clicking a node, I call a function that adds the node's child elements. So far so good. I now want to immediately invoke the click handler of one of the child elements to expand that too. My problem is that jQuery can't find the child elements that have just been added. When I step through in the debugger, my code to find the elements is being invoked before the new elements get rendered by the browser, which I'm guessing is the problem.

Is there some event I can wait for (similar to onload maybe) that marks when the newly added HTML is visible? Or a method I can call to force the rendering to take place earlier? Any suggestions would be welcome.

Note: I have since realised that the problem was entirely my fault, not the browser's or jQuery's. Please see my answer below.

like image 707
Charles Anderson Avatar asked Mar 10 '10 10:03

Charles Anderson


3 Answers

You can use .live() for this, rig your click handler to it instead of just .click() like this:

$(document).ready(function() {
  //instead of $(".myTreeNode").click(....
  $(".myTreeNode").live('click', function() {
    //Do stuff
  });
});

A .click() binds event handlers to the elements it finds when it's executed, so new elements don't have the handler. .live() instead listens up at the DOM level for clicks to bubble up, so it doesn't matter if they're added now or later. In the case of a lot of elements, you also have event handler instead of 1 for every element, after a few elements, this becomes more efficient as well.

like image 104
Nick Craver Avatar answered Nov 05 '22 16:11

Nick Craver


"live" is deprecated since jquery 1.7+ so Try this,

$(document).on("click","#Cancel" , function(){
 //do something
});

Visit http://api.jquery.com/on/ for more information

like image 26
mesut Avatar answered Nov 05 '22 18:11

mesut


I got round the problem eventually by using setTimeout() to delay my code until the new elements had been rendered. Not an ideal solution though, as the timeout period I've chosen is fairly arbitrary.

I have got to the bottom of it. The function I was calling that added the HTML was doing it asynchronously via a callback. So when I was trying to find the new HTML elements, they really weren't there yet. I have now altered my code so the callback is also responsible for processing the newly added elements, so guaranteeing that they'll be present.

like image 32
Charles Anderson Avatar answered Nov 05 '22 16:11

Charles Anderson