Dilwin
Dilwin

Reputation: 33

jQuery AJAX - target loaded content

How can I target dynamically loaded content with jQuery? I've read about it a lot an found the .live() function is an easy way to add an event to loaded content, but I'm not sure how to target objects within the loaded content. I've got a container on the main page:

<div id="container">place to load content</div>

and a container on the loaded page:

<div id="ajax-container">
    <div id="stuff">
        <div class="random-class">stuff to be loaded</div>
        <div class="random-links"><a href="#" class="delete">delete me</a></div>
    </div>
</div>

I have a link with the class 'delete' that I wanted to use to delete #stuff. I found out that jQuery will ignore the newer content, and therefore I could not attach an event to that anchor. I discovered the .live() function and that fixed my click problem.

$('.delete').live('click', function() {
    alert('click event works');
    $(this).parent('#stuff').hide();
});

The alert will fire, but how can I target div#stuff as well?

Upvotes: 0

Views: 1967

Answers (3)

Rafay
Rafay

Reputation: 31043

$('.delete').live('click', function() {
    alert('click event works');
    $(this).closest('div#stuff').hide();
});

here is the fiddle http://jsfiddle.net/5tCZH/

Upvotes: 2

rkj
rkj

Reputation: 566

Based on your code: Using .parent() only travels up one level in your DOM tree. Instead try to use the .parents() method to travel up multiple levels.

Upvotes: 0

Eddie
Eddie

Reputation: 10148

Not sure I understand, but $('#stuff') will get you the jQuery object for that Div regardless of where you call it. (lose the this.parent)

Upvotes: 1

Related Questions