Oleksandr IY
Oleksandr IY

Reputation: 3106

Can't make closest() and find() work

Can't make closest() and find() work:

<script type="text/javascript">
    $('a.favorites_save') .live('click', function(e) {
        thisObj = this;
        e.preventDefault();
        var link = $(this).attr('href')
        alert(link)
        $.get(link, function() {
            $(thisObj).find('a.favorites_delete:first').show();
            $(thisObj).hide();
        });
        return false;
    });

    $('a.favorites_delete') .live('click', function(e) {
        thisObj = this;
        e.preventDefault();
        var link = $(this).attr('href')
        $.get(link, function(data) { 
            $(thisObj).closest('a.favorites_save:first').show();
            $(thisObj).hide();
        });
        return false;
    });
</script>

HTML

<ul class="action-buttons">
    <li><a href="#link" class="portfolio">Add to portfolio</a></li>
    <span class="favorites_status"></span>
    <li><a class="favourites favorites_save" style="display:none;" href="/_web_includes/faves/reference/569">Add to Favourites</a></li>
    <li class="current"><a class="favourites favorites_delete" href="/_web_includes/faves/reference/569/delete">Remove Favourite</a></li>

When I press Remove Favourite it hides a link but show() doesn't work, the same with find() method. The HTML code repeated in the HTML sources just can't bring it all.

Upvotes: 2

Views: 578

Answers (3)

Oleksandr IY
Oleksandr IY

Reputation: 3106

The solution is something like that

$(thisObj).closest("ul").find('favorites_delete');

Just need up higher on the tree

Upvotes: 0

xCRKx TyPHooN
xCRKx TyPHooN

Reputation: 808

You are referencing the .find() and .closest() from within $(this) object. .closest() will only find parents to this object, while .find() will find children of this object. If you want a global selection, just do this...

$("a.favorites_save:first")

and this for delete...

$("a.favorites_delete:first")

Upvotes: 2

ShaneBlake
ShaneBlake

Reputation: 11096

Because your links are inside a <li>, both '.find()' and '.closest()' will never see them. Those two only work up and down the same branch of the tree...

You need to do something like .closest('action-buttons').find('favorites_delete') to get it to work...

Upvotes: 2

Related Questions