Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add anchor to links using jquery

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...

like image 244
user2444417 Avatar asked Feb 17 '23 09:02

user2444417


2 Answers

Try this way:-

$(function () {
    $('#lang_menu li a').attr('href', function (_, oldHref) {
        return oldHref + "#page1";
    });
});

Demo

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;
    });
});

Demo2

like image 96
PSL Avatar answered Feb 18 '23 23:02

PSL


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";
});
like image 40
j_mcnally Avatar answered Feb 18 '23 23:02

j_mcnally