user2344345
user2344345

Reputation: 1

Cannot change href attribute with jQuery

I am accessing links on a webpage with jQuery, with the following code:

$('a[href]').each(function() {
  $(this).attr('class', 'visited');
  $(this).attr('href', '#');
})

The class on the link will be changed, but the href will not. Is there something preventing me from changing/altering the href?

Edit:

I updated the code to the following:

$('a[href]').each(function() {
        $(this).addClass('visited');
        this.href = '#';
        })

However, although it works on MOST websites, it doesn't work on news.yahoo.com. Any reasons why this is so?

Upvotes: 0

Views: 982

Answers (2)

PSL
PSL

Reputation: 123739

You don't need to use jquery wrapper over this to do this:- You can just access href as a property from this itself as it represents the dom element.

$('a[href]').each(function() {
 ...
   this.href ="#";
})

Upvotes: 3

Michael Geary
Michael Geary

Reputation: 28850

For the href, you probably want to use .prop() instead of .attr().

For the classname, in most cases you want to use .addClass() instead of overwriting the entire class attribute.

Upvotes: 3

Related Questions