Dee
Dee

Reputation: 3255

jQuery add # to all internal links

Can someone tell me how to add hashes to all the internal links on a page?

For example:

page.html > page.html#

Thank you, d

Upvotes: 1

Views: 2618

Answers (4)

user113716
user113716

Reputation: 322622

If you're saying you only want to add # to links that are to pages within the same domain, you can compare the hostname of window.location to that of the link:

$("a").attr("href", function(i, href) {
    if( window.location.hostname === this.hostname ) {
        return href + "#";
    }
});

Upvotes: 4

Twoquestions
Twoquestions

Reputation: 488

Perhaps you could try this:

$(document).ready(function() {
    var attr = $('a').attr('href');
    attr = attr + '#';
    $('a').attr('href', attr);
});

Upvotes: -2

James Sumners
James Sumners

Reputation: 14783

$("a").each(function() {
  $this = $(this);
  $this.attr("href", $this.attr("href") + "#");
});

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630637

You can pass a function to .attr() like this:

$("a").attr("href", function(i, href) { return href + "#"; });

Though...I'm not sure on your reasoning for this, do you want to scroll to the top of the current page? In that case you can use .scrollTop() with a setter, like this:

$("a").click(function() { $("html, body").scrollTop(0); });

Or .animate() it:

$("a").click(function() { $("html, body").animate({scrollTop: 0 }, 500); });

Upvotes: 3

Related Questions