I'm new to javascript. Need to remove any existing anchors (eg: #page33) add other anchor (eg: #page1) to all links in a list dynamically (client side) with javascript or jquery:
Initial html (from server):
<ul id="lang_menu">
<li><a href="home.php?lang=eng#page33">English</a></li>
<li><a href="home.php?lang=tam#page33">Tamil</a></li>
<li><a href="home.php?lang=sin#page33">Sinhala</a></li>
</ul>
this should behave like (replace #page33 with #page1 at client side):
<ul id="lang_menu">
<li><a href="home.php?lang=eng#page1">English</a></li>
<li><a href="home.php?lang=tam#page1">Tamil</a></li>
<li><a href="home.php?lang=sin#page1">Sinhala</a></li>
</ul>
This is where I need this Developing Website
Please help me. Thanks in advance...
Try this way:-
$(function () {
$('#lang_menu li a').attr('href', function (_, oldHref) {
return oldHref + "#page1";
});
});
For your updated question you can try something like this:
using regex to replace the #part from the url.
$(function () {
$('#lang_menu li a').attr('href', function (_, oldHref) {
oldHref = oldHref.replace(/\#(.*)/g, "#page1");
if(oldHref.indexOf('#') == -1)
oldHref += "#page1";
return oldHref;
});
});
If you are dealing with a lot of DOM elements its less expensive to add the anchor lazily.
jQuery("a").bind("click", function(e) {
e.preventDefault();
document.location = jQuery(this).attr("href") + "#page1";
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With