simPod
simPod

Reputation: 13466

jQuery selector for links with # in href attribute

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)

Upvotes: 31

Views: 58835

Answers (3)

Korvin Szanto
Korvin Szanto

Reputation: 4501

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

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

Check out my jsfiddle!

Upvotes: 19

Adam Rackis
Adam Rackis

Reputation: 83356

*= 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 #

Upvotes: 51

epignosisx
epignosisx

Reputation: 6192

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

Upvotes: 70

Related Questions