2
//Images
var boxlinks = $('a[href]').filter('[href$=".png"], [href$=".gif"], [href$=".jpg"], [href$=".jpeg"]');

Is there a more efficient way to select multiple values of a single attribute with a filter in jQuery, here I am trying to select links only with an image as an href.

2
  • filter() can accept a method as its input. So in theory you could make a regex check against the href to see if it ends in any of the extensions. Or if possible, you could throw an 'image' class on all of them and call it a day. Commented Jan 8, 2019 at 23:50
  • Can't do the class - was thinking regex also looking for a way to implement that. Commented Jan 9, 2019 at 0:14

1 Answer 1

2

Here is an example that uses a regex and a class. The regex lowercases the href so it's insensitive.

var boxlinks = $('a[href]').filter(function(){
      // regex checks for a literal period, followed by one of the extensions, and then
      // the end of the line
  return /[.](png|gif|jpg|jpeg)$/.test(this.href.toLowerCase());
});

console.log(boxlinks.get());
console.log($('a.image').get());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="https://stackoverflow.com/something/something/thing.txt"></a>
<a href="https://stackoverflow.com/something/something/thing.png" class="image"></a>
<a href="https://stackoverflow.com/something/something/thing.gif" class="image"></a>
<a href="https://stackoverflow.com/something/something/thing.jpg" class="image"></a>
<a href="https://stackoverflow.com/something/something/thing.jpeg" class="image"></a>
<a href="https://stackoverflow.com/something/something/thing.PNG" class="image"></a>
<a href="https://stackoverflow.com/something/something/thing.GIF" class="image"></a>
<a href="https://stackoverflow.com/something/something/thing.JPG" class="image"></a>
<a href="https://stackoverflow.com/something/something/thing.JPEG" class="image"></a>

Sign up to request clarification or add additional context in comments.

1 Comment

Very nice, also didn't think of the case conversion, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.