Search code examples
jqueryurlreplacehref

jQuery replace href and change url in every <a>


I'm new to jQuery and I'm trying to replace numerous link by another one, but I can't seem to find why it doesn't, could you help me please.

Code:

First attempt:

jQuery(document).ready(function() {

    $("a").each(function() { 

        newUrl += $(this).href+ textOfNew + " ";

        this.href = this.href.replace((this.href), newUrl);

    });

});

Second attempt:

jQuery(document).ready(function() {

    $("a").each(function() { 
        $("$(this).href").val(function(i, val) {
            var newUrl = "test" ;

            return = $(this).href.replace($(this).href, newUrl);
        }); 
    });
}); 

Solution

  • try this

       $("a").each(function() { 
    
              var newUrl =  $(this).attr('href')+ textOfNew + " ";
    
                  $(this).attr('href',newUrl);
    
        });