3

I know how to hijack a link in jQuery, and I know how to find an element's parent, but I can't seem to combine the two. I have multiple divs, each of which contains a link. I want to hijack the link and update the parent div's content.

<div class="container-1">
  <a href="/foo.html">Add content</a>
</div>
 <div class="container-2">
  <a href="/bar.html">Add content</a>
</div>

Here's what I have with jQuery:

$(function() {
    $(".pager A").live("click",
    function() {
        $.get($(this).attr("href"),
        function(response) {
            $(this).parent().attr("id").replaceWith(response); // This is wrong
        });
        return false;
    });
});

The line with the "This is wrong" comment doesn't have what I want for $(this). It appears to contain the result from the previous expression, not the element I selected (".pager A").

How can I do this?

Bonus question: Visual Studio complains that ".get is a reserved word and should not be used as an identifier". What exactly is the problem?

EDIT: Sorry, I meant <div id="container-1">, not <div class="container-1">. Ditto for the 2nd div.

2
  • fwiw, $(this).parent().attr("id").replaceWith(response) .. doesn't look right to me . Oct 4, 2009 at 5:53
  • RE: your edit - try my updated example. if it's not what you want keep traversing, or tell us what the actual response is. Oct 4, 2009 at 6:13

2 Answers 2

4

Try saving the reference to the current execution context where it points to the anchor to refer to later in the callback:

$(function() {
    $(".pager A").live("click",
    function() {
        var el = this;
        $.get($(el).attr("href"),
        function(response) {
            $(el).parent().html( response ); // is this what you want? .attr('id') would return a string and you can't call jQuery methods on a string.
        });
        return false;
    });
});
0
0

First of all:

    $(function() {
      $(".pager A").live("click",
        function() {
          var $link = $(this);
            $.get($(this).attr("href"),
            function(response) {
              $link.parent().attr("id").replaceWith(response); // This is wrong
            });
          return false;
        });
    });

You shouldn't use $(this) in callback function.

And the second - your link's parent element doesn't have id attribute. If you want to replace it's content use something like html() or text()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.