Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace element's attr href with each

I want to change the href URL from the HTML string.

But it prints the old URL instead of the test.php

var html='<div><a href="https://www.spectrum.net/support/manage-account/creating-username?cid=eml_ehh_60_0621">find out how</a></div>';

$(html).find('a').each(function(){
    var newUrl = "test.php";
    $(this).attr("href", newUrl);
});
console.log(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

OUTPUT:
<div><a href="https://www.spectrum.net/support/manage-account/creating-username?cid=eml_ehh_60_0621">find out how</a></div>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It prints the same URL it’s not changing to the new URL test.php

EXPECTED OUTPUT:
<div><a href="test.php">find out how</a></div>

>Solution :

Use replace to change URL.

Example:

var html = '<div><a href="https://www.spectrum.net/support/manage-account/creating-username?cid=eml_ehh_60_0621">find out how</a></div>';

$(html).find('a').each(function(i, ...v) {
  var Url = $(this).attr('href');
  var newUrl = "test.php";
  html = html.replace(Url, newUrl);
});
console.log(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading