Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to replace href link using javascript

I have lots of pages with lots of links. I want to replace some specific links with another link.

what I wish to do here is find the href attribute of <a> and replace it with desired link

Here is the HTML code

<div class="one">
     <div class="item">
         <a href="somelink.com">click</a>
     </div>
</div>

and I want to change HTML to

<div class="one">
     <div class="item">
         <a href="replacedlink.com">click</a>
     </div>
</div>
like image 815
parish Avatar asked Mar 17 '17 09:03

parish


3 Answers

One way could be is to use the href value to find the anchor

var a = document.querySelector('a[href="somelink.com"]');
if (a) {
  a.setAttribute('href', 'replacedlink.com')
}
<a href="somelink.com" title="this link">
</a>
like image 88
shubham agrawal Avatar answered Oct 07 '22 01:10

shubham agrawal


Try this

$('.item a').attr('href').replace('somelink.com', "replacedlink.com");

OR

$(".item a[href='somelink.com']").attr("href", "replacedlink.com");

With jQuery 1.6 and above you should use:

$(".item a[href='somelink.com']").prop("href", "replacedlink.com");
like image 35
NID Avatar answered Oct 07 '22 01:10

NID


Try This:

$(".item a[href='somelink.com']").attr('href','replacedlink.com');
like image 1
Akshey Bhat Avatar answered Oct 07 '22 02:10

Akshey Bhat