5

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>
parish
  • 846
  • 2
  • 18
  • 32

6 Answers6

6

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>
shubham agrawal
  • 3,435
  • 6
  • 20
  • 31
4

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");
NID
  • 3,238
  • 1
  • 17
  • 28
1

Try This:

$(".item a[href='somelink.com']").attr('href','replacedlink.com');
Akshey Bhat
  • 8,227
  • 1
  • 20
  • 20
0

Use .attr attribute to do this. Please follow below code::

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

For more information related to .attr attribute please go through this link.

Rana Ghosh
  • 4,514
  • 5
  • 23
  • 40
0

Here try this:

https://jsfiddle.net/2sqxaxqs/

$('a.btn').click(function(e){
    e.preventDefault;
    var newHref = 'http://www.google.com';
  $('a.theLink').attr('href', newHref);
})

You can target the href using jQuery's attr.

jock.perkins
  • 469
  • 6
  • 23
0

$('a[href="somelink.com"]').attr('href', 'replacedlink.com');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="one">
     <div class="item">
         <a href="somelink.com">click</a>
     </div>
</div>
himyata
  • 338
  • 1
  • 9