views:

20

answers:

2

After load content to page using

div.load('page.php');

I need get all of links from page to change them. So I wrote this:

div.load('page.php', function() {
    links = $('a');
    alert(links.length);

    for(i=0 ; i<links.length ; i++
    {
        link = $('a:nth-child('+(i+1)+')');
        alert(link.attr('href'));
    }
});

The result of this code is: - first alert() returned correct links quantity, but it's not a DOM objects, so I can't change href attribute using it: links[i].attr('href', 'changed') and I have to getting links in loop one by one, but this method returned only first link from page.php and all of links from site which will not changed.

Have someone any idea how do it?

A: 

If you need to modify all the links only in the content that was loaded, use a context, like this:

div.load('page.php', function(data) {
  $('a', data).attr('href', '#');
});
//or, if they're interdependently changed, something like this...
div.load('page.php', function(data) {
  $('a', data).attr('href', function(i, href) {
    return href + "?tracking=1"; //append ?tracking=1
  });
});

This finds all <a>, but only inside the response that came back for page.php, so only the anchors that you just loaded. The format is $(selector, context), if you leave context off, it's document, so something like $('a') is really $(document).find('a'), giving it a context other than document, you're saying $(data).find('a'), getting only the links you want.

Nick Craver
+1  A: 

You can do like:

div.load('page.php', function() {
    $('a').each(function(index){
      alert($(this).attr('href'));
    });
});

You can change their href like:

div.load('page.php', function() {
    $('a').each(function(index){
      $(this).attr('href', 'whatever');
    });
});
Web Logic
Thanks! It solved my problem.
kodziek