30

I need a pattern that will traverse the document and get me all links that have mailto in their href:

<a href="mailto:an@email.com">text</a>

I could of course easily get all a elements ($("a")) and check each href attribute to see if it points to a mailto but I think that jQuery has some form of pattern matching that will allow me to do just that.

What is the best way to achieve that?

Andreas Grech
  • 105,982
  • 98
  • 297
  • 360

1 Answers1

69
$('a[href^="mailto:"]')

Double quotes are usually redundant, but needed in this special case, because : would otherwise be interpreted as the start of a pseudo-selector. So $('a[href^=mailto]') would also work, but in this particular scenario, the quotes are probably a neater way to go.

David Hedlund
  • 128,221
  • 31
  • 203
  • 222
  • 1
    I'm getting an error unless I wrap `mailto` in double quotes, like this `$('a[href^="mailto:"]');` – tmslnz Oct 07 '11 at 18:58
  • @tmslnz: Good catch! It's the `:` that necessitates the quotes. Updated. – David Hedlund Oct 09 '11 at 14:46
  • @KrishnaprasadVarma: That's not very informative. [The code works](http://jsfiddle.net/ZbRPj/). Something is wrong with your markup, your jQuery, your selector, the time and/or scope of execution, or in how you treat the result. Seeing as OP considered this answer to answer the question, you may be better off creating a new question, if this answer doesn't apply to you. – David Hedlund Nov 06 '12 at 09:41
  • @David I am sorry. The code is working. I was having a conflict with prototype – Krishna Prasad Varma Nov 08 '12 at 10:00