Search code examples
javascriptjqueryevent-handlinglive

How do I add elements to the DOM and then refer to those added elements in Javascript/JQuery?


After adding elements to page using something like this,

$('#blah').append('<div id="bugsbunny"></div>');

how can I use javascript/jquery with that added element? Would the DOM tree have to be rebuild or something? I want to do something like this:

$('#bugsbunny').hide();

How can I get this to work? Is the logic wrong or is there another way to do this?

I have considered using .on or .live but these methods require an event such as "click". My code looks something like this:

$(document).ready(function(){
bamboo.addEventListener("load", dothisaction, false);
});

function thisHappensAtAnotherTime() {
$('#blah').append('<div id="bugsbunny"></div>');
}

function dothisaction(evt) {
     $('#bugsbunny').hide();
}

However, #bugsbunny doesn't disappear because it was appended after the page was loaded. What can I do?

Thanks in advance!

Edit: I updated what my code looks like.


Solution

  • $(function(){
        var rabbit;
    
        function thisHappensAtAnotherTime() {
            rabbit = $('<div id="bugsbunny" />');
            $('#elmer').append(rabbit);
    
            //no sure but i think  you can do it like:
            rabbit = $('<div id="bugsbunny" />').appendTo('#elmer');
        }
    
        function dothisaction(evt) {
             rabbit.hide();
        }
    });