parish
parish

Reputation: 856

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>

Upvotes: 6

Views: 34343

Answers (6)

NID
NID

Reputation: 3294

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

Upvotes: 4

himyata
himyata

Reputation: 338

$('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>

Upvotes: 0

jock.perkins
jock.perkins

Reputation: 469

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.

Upvotes: 0

Rana Ghosh
Rana Ghosh

Reputation: 4674

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.

Upvotes: 0

Akshey Bhat
Akshey Bhat

Reputation: 8545

Try This:

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

Upvotes: 1

shubham agrawal
shubham agrawal

Reputation: 3541

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>

Upvotes: 7

Related Questions