matt
matt

Reputation: 44303

jquery: add #hash to all links if it doesn't already have one?

hey guys, the following code works fine... I'm adding a #wpf-wrapper hash to all links that are inside of #wpf-wrapper.

$('#wpf-wrapper a').live('click',function() {
    $(this).attr('href', $(this).attr('href') + "#wpf-wrapper");        
});

However if there is a link that already has e.g. href="#" I don't want to add another one to it. Why is the following code not working?

$('#wpf-wrapper a').not('#wpf-wrapper a[href="#"]').live('click',function() 
    $(this).attr('href', $(this).attr('href') + "#wpf-wrapper");        
});

Suddenly none of my links gets this #wpf-wrapper added?

Upvotes: 1

Views: 2580

Answers (2)

user113716
user113716

Reputation: 322502

Here's another way:

$('#wpf-wrapper a').each(function(){ 
    if( !this.hash ) this.hash = "#wpf-wrapper";
});

You can use the native hash property on the a element to set it instead of using jQuery's .attr() method.


If the reason you're doing this inside the click handler, is that an .each() doesn't work, it's likely that you're running the code before the DOM is loaded.

If so, do this:

$(function() {
    $('#wpf-wrapper a').each(function(){ 
        if( !this.hash ) this.hash = "#wpf-wrapper";
    });
});

If you're creating the elements dynamically, add the hash when they're being created.

Upvotes: 1

hunter
hunter

Reputation: 63522

This selector is wrong

$('#wpf-wrapper a').not('#wpf-wrapper a[href="#"]')

should be this using the attribute contains selector with a proper :not() selector

$('#wpf-wrapper a:not([href*="#"])')

Upvotes: 5

Related Questions