BiberFiver
BiberFiver

Reputation: 167

How to select only links without `#`?

I want to select only links that do not contain anchors, like #. How do I do that?

Upvotes: 2

Views: 155

Answers (4)

Darm
Darm

Reputation: 5659

Use this code:

If you want to filter href="#":

$('a[href!="#"]')

Otherwise:

$('a').filter(function(){
    return !/#/.test(this.href);//you can filter what you do not want with the regex
})

Upvotes: 0

Paul
Paul

Reputation: 141827

This will select all anchors whose href attribute does not begin with #.

$('a:not([href^="#"]');

It could be a slow selector. Are you using it only once or multiple times? You can speed it up a little like:

$('a').not('[href^="#"]');

If you also do not want to select anchors which contain a #anywhere, rather than just the beginning you can change the ^ to a *. But this will also not select links that reload the browser (going to a different page and then to a named anchor on that page). I don't think that's want you want, but I'm not positive now.

Upvotes: 3

Andrew Hare
Andrew Hare

Reputation: 351526

Try this:

$(':not(a[href*="#"]));


This will be faster (and will select only anchors as well):

$('a:not([href*="#"])');

Upvotes: 2

zzzzBov
zzzzBov

Reputation: 179086

I'm so surprised by all the fast answers, as most of them don't actually do what was asked for.

$('a:not([href*="#"])');

Should select links that don't contain "anchors" or as I assume OP meant: in-page anchor/id tags.

Upvotes: 2

Related Questions