1

I tried to look after a similar problem but couldn't find any here. So here is my problem. I have a structure with multiple h2. Each h2 have an image inside that points to a different url. I need to fetch this url from each image and assign it to the correspondent h2.

Here is my code (this one works, but it only fetches the first link):

    $("h2").each(function() {

        var $link = $('a[rel=example_group]').attr("href");

        $(this).append($link);
    });

So I tried this:

    $("h2").each(function() {

        var $link = $('a[class=button zoom]').each(function(){$(this).attr("href")});


        $(this).append($link);
    });

but it is not working

Could you help? Thanks

1
  • Can you post some sample HTML as well. Commented Jun 27, 2011 at 13:23

4 Answers 4

3
$("h2").each(function(i,n) {

        var $link = $(n).find('a[rel=example_group]').attr("href");


        $(n).append($link);
    });

try this....

Sign up to request clarification or add additional context in comments.

Comments

2

howabout

$("h2").each(function() {

    var $link = $(this).find('a[class=button zoom]').attr("href")});


    $(this).append($link);
});

2 Comments

need to learn to type faster! some good answers already proposed.
thank you everyone guys! seems that each solution have the truth in it. It actually was a simple job and I found the solution. Thanks!
2

The problem is that you are not scoping your search for the a tag. Just cache $(this) and do a find use it and it should work for you:

$("h2").each(function() {
    var h2 = $(this),
        $link = h2.find('a[rel=example_group]').attr("href");

    h2.append($link);
});

Comments

2

In your first example you always append the same link over each iteration. Not sure what you're trying to do with the second example.

In your first example try to just add a context to your selector changing:

var $link = $('a[rel=example_group]').attr("href");

by

var $link = $('a[rel=example_group]',this).attr("href");

and it should work.

You also can do something like:

$("h2 a[rel=example_group]").each(function() {
    var $link = $(this).attr('href');
    // ... do what you need with $link ...//
});

It should work too if i understand well your request.

1 Comment

i like your answer with that selector however, this inside a each function? don't think it would work :)but hey ...

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.