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>
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>
3
Answers
The issue you are facing is that you are modifying the HTML string html, but you are not updating the original HTML content of the element. When you use $(html), it creates a new jQuery object with the HTML string, but the changes you make with .attr() are not affecting the original html variable.
To achieve the expected output, you need to modify the html variable directly by updating the href attribute before converting it to a jQuery object. Here’s how you can do it:
Now, updatedHtml will contain the expected output:
By updating the jQuery object and then converting it back to an HTML string, you retain the changes made to the href attribute.
Use replace to change URL.
Example:
you can use this if you want to apply it on HTML: