Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 784
Ben Potter Avatar asked Feb 23 '12 03:02

Ben Potter


1 Answers

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/

like image 107
djd Avatar answered Sep 30 '22 19:09

djd