2

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.

Colin Brock
  • 21,267
  • 9
  • 46
  • 61
Oleksandr IY
  • 2,783
  • 6
  • 32
  • 53

3 Answers3

2

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...

ShaneBlake
  • 11,056
  • 2
  • 26
  • 43
2

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")
xCRKx TyPHooN
  • 808
  • 5
  • 18
  • will it always select the first global a.favorites_save? I need to show/hide related selectors – Oleksandr IY Feb 01 '12 at 17:52
  • This selector will select the first global a.favorites_save. If you need to select the reference in
      you can do something like @ShaneBlake suggested. $(thisObj).closest("ul").find('favorites_delete');
    – xCRKx TyPHooN Feb 01 '12 at 18:33
  • yes this is solution, I was about to answer my question just my reputation is too low so i have to wait 8 hours. Thanks – Oleksandr IY Feb 01 '12 at 19:18
0

The solution is something like that

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

Just need up higher on the tree

Oleksandr IY
  • 2,783
  • 6
  • 32
  • 53