Ben Potter
Ben Potter

Reputation: 875

jQuery replace all href="" with onclick="window.location="

So I have a cool one for ya.

I need to scan my html document as it is rendering and replace every

href=""

with

onclick="window.location=''"

more than that, I need to carry the link from the href to the window.location.

For example, if I had:

href="http://www.google.com.au"

it would become:

onclick="window.location='http://www.google.com.au'"

and I need it to do this on every href in the document


I have no idea, but it needs to be in jQuery / javascript :D

Thanks guys.

Upvotes: 6

Views: 52573

Answers (3)

RobG
RobG

Reputation: 147363

Some non-jQuery variants:

Keep href:

var i = document.links.length;
while (i--) 
  document.links[i].onclick = function(){window.location = this.href;};

Keep href and don't follow it if onclick called (even though it goes to the same place):

var i = document.links.length;
while (i--) 
  document.links[i].onclick = function() {
    window.location = this.href;
    return false;
  };

Remove href:

var i = document.links.length,
    link;
while (i--) {
  link = document.links[i]; 
  link.onclick = (function(href) {
    return function() {
        window.location = href;
    }(link.href));
  link.href = '';
}
link = null;

Of course I don't understand why you want to replace a robust, works everywhere solution with an unreliable, easily broken one.

Upvotes: 2

alex
alex

Reputation: 490163

This should achieve what you want...

$('a[href]').click(function(event) {
   event.preventDefault();
   window.location = this.href;
});

I assume you wanted to prevent default behaviour of links.

For all possible links, you could use document.links.

For all links and future links, use event delegation.

$('body').on('click', 'a[href]', function() {
       window.location = this.href;
});

Upvotes: 3

djd
djd

Reputation: 5178

You could try this:

$('a').each(function() {
  var href = $(this).attr('href');
  $(this).attr('onclick', "window.location='" + href + "'")
         .removeAttr('href');
});

What are you trying to achieve with this? Chances are that there's a more elegant way to achieve what you're after.

For example, it might be better to handle the event yourself in the JS. Replace the third line with:

$(this).click(function() { window.location = href; })

That could become very expensive though, so you might want to consider jQuery's delegate events: http://api.jquery.com/delegate/

Upvotes: 9

Related Questions