Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access jquery element after append function

Tags:

jquery

I use append function in order do add some div into another element

('#test-append').append("<div class='new_div'><b>some text</b></div>")

everything is going fine and I can see the added div,`but I also need after that to access the div selector in order to do something with this div for example to hide it so i use the folowing

$('.new_div').click(function(){
            do somthing here
        });

but it is not working even if I just use simple alert('hi') call. It seems like jquery doesn't recognize the append class (I also tried it with Id and I get the same result)

I will appreciate some help on this issue

Thanks

like image 824
winter sun Avatar asked Feb 22 '12 21:02

winter sun


3 Answers

before jquery 1.7 you needed to use live() or delegate() to bind events to elements ignoring whether they existed at the time of binding or not.

since jquery 1.7, you can use

$('root-element').on('click', 'selector', function () { do it })

above is edited as per jaspers comments

like image 120
mindandmedia Avatar answered Sep 29 '22 11:09

mindandmedia


You could append the element, then select it as it will be a child element of the original selection:

$('#test-append').append("<div class='new_div'><b>some text</b></div>").children('.new_div').click(...);

Or you could use .appendTo() which appends the element(s) but also keeps them selected:

$("<div class='new_div'><b>some text</b></div>").appendTo('#test-append').click(...);

Or as others have stated you can save a reference to the element in a variable and then use that variable at a later time to manipulate the element:

var $element = $("<div class='new_div'><b>some text</b></div>").appendTo('#test-append');
$element.click(...);//but you could have just chained the call like the previous example
like image 27
Jasper Avatar answered Sep 29 '22 11:09

Jasper


Maybe this is not recommended method... but it works (jQuery 2.1.3)

$('.current_element').append("<div class='future_element'><b>some text</b></div>").find('.future_element').click(function(){
    console.log('you can see me if you click appended element');
});

and version when we append element on click

$('.current_element').click(function(){
    $('body').append("<div class='future_element'>anything</div>");
    $('.future_element').click(function(){
        $(this).text('do something with appended element'); //for example
    });
});
like image 29
Dariusz Majchrzak Avatar answered Sep 29 '22 12:09

Dariusz Majchrzak