31

I tried to use this jQuery selector:

$("a:has(href*=#)").click(function() {
     alert('works');
});  

but it doesn't seem to work. I would like to select all tags which have anchor in href attribute (has # symbol there)

simPod
  • 11,498
  • 17
  • 86
  • 139

3 Answers3

70
$("a[href*=#]").click(function(e) {
    e.preventDefault();
    alert('works');
});  
epignosisx
  • 6,152
  • 2
  • 30
  • 31
51

*= will filter attributes that contain the given string anywhere

$("a[href*='#']").click(function() {
    alert('works');
});

Also note that

$("a[href^='#']").click(function() {
    alert('works');
});

will select any anchor whose href starts with a #

Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
19

You've got to select using the attribute starts with selector:

$('a[href^="#"]').click(function(){
    alert('Works!');
});

Check out my jsfiddle!

Korvin Szanto
  • 4,531
  • 4
  • 19
  • 49