tags:

views:

36

answers:

3

Hi,

I discovered that .attr() only applies to the first matched element on the page! So, I've been trying to get the hrefs from all the matched elements on a page, but to no avail.

Here's what I tentatively wrote:

    var thelinks = $("td a").each(function(){
    $(this).attr("href");
    document.write(thelinks);
});

I used document.write just to see what was going on, and I got a long list of "undefinedundefinedundefined"

What I'm trying to do is extract the hrefs from each td a and then use ajax to visit those pages and do other stuff. I can get it work fine when it's dealing with just one link, but this multiple elements thing I can't figure out.

Any help rendered is appreciated, I'm a novice to the world of Javascript and Jquery.

+3  A: 

Change your code to

var thelinks = $("td a").map(function(){
    return $(this).attr("href");});

document.write(thelinks);

You're trying to print out the content of "thelinks" inside the anonymous function that defines it.

David
+1  A: 

You could simplify this to this, you have some extra code and your variable is not defined properly:

$("td a").each(function(){
    document.write($(this).attr("href"));
});
jarrett
+2  A: 

Your code doesn't make sense; first, each doesn't have a useful return value (you want map instead), and second, you're printing thelinks before it's been assigned any value whatsoever.

Probably you want something like this:

var thelinks = $("td a").map(function () {
  return $(this).attr("href");
}).get();

// Just for example purposes
document.write( thelinks.join(", ") );
hobbs