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

So, I have a cool one for you.

I need to scan my html document as it renders and replaces each

href=""

with

onclick="window.location=''"

Moreover, I need to transfer the link from href to window.location.

For example, if I had:

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

he will become the following:

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

and I need to do this for every href in the document


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

Thanks guys.

+5
source share
3 answers

You can try the following:

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

What are you trying to achieve with this? Most likely, there is a more elegant way to achieve what you need.

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

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

, jQuery delegate: http://api.jquery.com/delegate/

+8

, ...

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

, .

document.links.

.

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

, jQuery:

href:

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

href , onclick ( ):

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

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;

, , , .

+2

All Articles