Faisal Khurshid
Faisal Khurshid

Reputation: 1909

jQuery: select all internal links EXCLUDING links to downloadable files

I'm using following piece of jQuery code to select all internal links ...

var siteURL = "http://" + top.location.host.toString();
var $internalLinks = $("a[href^='"+siteURL+"'], a[href^='/'], a[href^='./'], a[href^='../'], a[href^='#']");

and it works just fine. The only problem i'm facing is that i don't want to select internal links which directly points to downloadable files (e.g. http://www.example.com/downloadable.pdf)

Extension could be anything (pdf, mp3, jpg, gif, webm ... etc)

Now question is, how to exclude such internal links from the above criteria?

Or if i use .not() function to exclude such links, question would be, how to select all internal links which directly points to such downloadable files?

Upvotes: 3

Views: 2559

Answers (3)

user229044
user229044

Reputation: 239501

A simple solution would be to use a filter or not with a regular expression to reject the links you don't want:

var $internalLinks = $("a[href^='"+siteURL+"'], a[href^='/'], a[href^='./'], a[href^='../'], a[href^='#']");

$internalLinks = $internalLinks.not(function () {
  return $(this).attr('href').match(/\.(pdf|mp3|jpg|jpeg|etc)$/i);
});

The opposite, assuming all of your "not downloadable" URLs end in .html or .htm, would be to filter for links with those extensions:

$internalLinks = $internalLinks.filter(function () {
  return $(this).attr('href').match(/\.html?/);
});

Upvotes: 4

Matt
Matt

Reputation: 131

You can chain a .not() method to your selection and use the ends with selector. E.g.

$("a[href^=something]").not("[href$=pdf]")

http://api.jquery.com/not/

http://api.jquery.com/attribute-ends-with-selector/

Working jsFiddle example: http://jsfiddle.net/uPps6/

Upvotes: 1

Zeth
Zeth

Reputation: 875

If you have a list of filetypes in use, you could use .not. Untested:

$internalLinks = $internalLinks.not($('a[href$=".mp3"]')...

Upvotes: 0

Related Questions