Airikr
Airikr

Reputation: 6436

How to get value from each href on the page, with jQuery?

var href = $('a[target="_blank"]').attr('href'); $('a[target="_blank"]').attr('title', 'Öppnas i en ny flik; ' + href);

Let's say I have a link in the header.php file with target="_blank". In the donate.php file I have another link with target="_blank". The code I show you above does only take the href value from the link in the header.php file. How do I take the href value in every link I have on the current page?

If I have the mouse cursor over the link in header.php, it will show "Öppnas i en ny flik; http://the-link.nu/". If I have the mouse cursor over the link in donate.php, it will show "Öppnas i en ny flik; http://another-link.nu/".

Any help to fix this problem? :) Thanks in advance!

Upvotes: 1

Views: 1226

Answers (2)

J Bryan Price
J Bryan Price

Reputation: 1384

$('a[target="_blank"]').each(function() {
    $(this).attr('title', 'Öppnas i en ny flik; ' + $(this).attr('href'));
});

You're only getting the first anchor's attribute because $.attr() is designed to get just the value from the first matched element. Using $.each lets you loop through all of the elements found.

Upvotes: 0

mutex
mutex

Reputation: 7728

use jquery each method:

$('a[target="_blank"]').each(
    function() {
        var href = $(this).attr('href');
        $(this).attr('title', 'Öppnas i en ny flik; ' + href);
    }
);    

Upvotes: 1

Related Questions