JQuery extension for link changes
I have a link to so many pages. For instance:
<ul>
<li> <a href="someurl/somefile.html"> Some file </a> </li>
<li> <a href="someurl/somefile1.html"> Some file1 </a></li>
<li> <a href="someurl/somefile2.html"> Some file2 </a></li>
</ul>
<a href="someurl/someotherfile.html"> Some Other file </a>
<a href="someurl/someotherfile1.html"> Some Other file1 </a>
Now I want to change the extension htmlto php. without changing the code php.
I tried the following code but it does not work.
$('a').each(function() {
$(this).html( $(this).html().replace( ".php", '.html' ) );
});
Any help would be appreciated.
There are two problems in the code:
1) You need to change the href attribute, not the html elements
2) You replaced the arguments for replacing html with php. the first argument must be for matching, and the second for replacing it.
$('a').attr('href',function(i,oldhref) {
return oldhref.replace( ".html",'.php');
});
Working fragment:
$(function(){
$('a').attr('href',function(i,oldhref) {
return oldhref.replace( ".html",'.php');
});
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li> <a href="someurl/somefile.html" target="_blank"> Some file </a> </li>
<li> <a href="someurl/somefile1.html" target="_blank"> Some file1 </a></li>
<li> <a href="someurl/somefile2.html" target="_blank"> Some file2 </a></li>
</ul>
<a href="someurl/someotherfile.html" target="_blank"> Some Other file </a>
<a href="someurl/someotherfile1.html" target="_blank"> Some Other file1 </a>Just use replaceas below:
$(document).ready(function() {
$('a').each(function() {
$(this).attr('href',$(this).attr('href').replace('html','php') );
});
})<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li> <a href="someurl/somefile.html"> Some file </a>
</li>
<li> <a href="someurl/somefile1.html"> Some file1 </a>
</li>
<li> <a href="someurl/somefile2.html"> Some file2 </a>
</li>
</ul>
<a href="someurl/someotherfile.html"> Some Other file </a>
<a href="someurl/someotherfile1.html"> Some Other file1 </a>