Benjamin Morrison
Benjamin Morrison

Reputation: 791

Add Current Page URL Before Anchor Link Using jQuery

I am stuck utilizing a platform (Nationbuilder) that automatically adds the base tag in the header. It didn't until recently and now the dozens of pages with anchor links end up sending the user to the homepage.

I need to use jQuery to add the current page's url before the #anchor. The closest I can find is the following code, but I have no idea how to modify it so ONLY links with a href attribute starting with a # are modified:

$("a").attr("href", "http://www.example.com/pageslug")

So I would like:

<a href="#anchorname"></a>

To be changed to:

<a href="http://www.example.com/pageslug#anchorname"></a>

Upvotes: 0

Views: 1613

Answers (3)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276306

You can use the CSS attribute starts with selector:

Instead of selecting "a", select 'a[href^="#"]' meaning "a tags with an href attribute starting with #.

So something like:

$('a[href^="#"]').each(function(i,el){
    el.href = "http://www.example.com/pageslug" + el.hash;
});

(fiddle)

Upvotes: 4

Novaugust
Novaugust

Reputation: 318

One addition to what Benjamin said, you'll need to capture the current href for each of the anchors, which means you need a loop. So

$('a[href^="#"]').each(function(index, element){
    var $ele = $(element),
        oldHref = $ele.attr('href');
    $ele.attr('href', '//example.com/page'+ oldHref);
});

Upvotes: 3

Izaaz Yunus
Izaaz Yunus

Reputation: 2828

Something like this?

$('a').attr('href', window.location.pathname + this.attr('href'))

Upvotes: 0

Related Questions