Reputation: 518
I have set of following links in so many pages.
Following are the php file which have code .i.e.:
Input :
<a href="someurl/someotherfile.html"> Some Other file </a>
<a href="someurl/someotherfile1.html"> Some Other file1 </a>
<p><a href="someurl/someotherfile2.html"> Some Other file2 </a></p>
<div><a href="someurl/someotherfile2.html"> Some Other file2 </a></div>
<span><a href="someurl/someotherfile2.html"> Some Other file2 </a></span>
Output :
<a href="someurl/someotherfile.php"> Some Other file </a>
<a href="someurl/someotherfile1.php"> Some Other file1 </a>
<p><a href="someurl/someotherfile2.php"> Some Other file2 </a></p>
<div><a href="someurl/someotherfile2.php"> Some Other file2 </a></div>
<span><a href="someurl/someotherfile2.php"> Some Other file2 </a></span>
Now, I want to change the html to php extension in href attribute. without modifying the php code.
I have try following code but it does not work. Noting to happen in this code.
$('a').each(function() {
$(this).html( $(this).html().replace( ".php", '.html' ) );
});
Upvotes: 2
Views: 102
Reputation: 6539
You should write:-
$('a').each(function() {
var hrefVal = $(this).attr('href');
$(this).prop("href", hrefVal.replace( ".html", '.php' ) );
});
Check this link prop vs attr.
Upvotes: 0
Reputation: 26153
You can change url while a link to be clicked. Clear JS seems to be faster
function replaceHref() {
this.href = this.href.replace('.html','.php');
return true;
};
window.onload = function() {
var arr = document.getElementsByTagName('a');
for(i=0; i < arr.length; i++)
arr[i].onclick = replaceHref;
};
Upvotes: 0
Reputation: 8101
Try:
Use attr('href',value)
to set new href and use .replace
to replace html to php
$( document ).ready(function() {
$('a').each(function() {
$(this).attr('href',$(this).attr('href').replace( ".html", '.php'));
});
});
Upvotes: 4
Reputation: 10177
.html()
changes the content inside the <a>
tag not the content inside the href
you need to change the href
value.
$('a').each(function() {
$(this).attr('href', $(this).attr('href').replace(".html", ".php"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="someurl/someotherfile.html"> Some Other file </a>
<a href="someurl/someotherfile1.html"> Some Other file1 </a>
<p><a href="someurl/someotherfile2.html"> Some Other file2 </a>
</p>
<div><a href="someurl/someotherfile2.html"> Some Other file2 </a>
</div>
<span><a href="someurl/someotherfile2.html"> Some Other file2 </a></span>
Upvotes: 0