最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - how to replace href link using javascript - Stack Overflow

programmeradmin5浏览0评论

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">click</a>
     </div>
</div>

and I want to change HTML to

<div class="one">
     <div class="item">
         <a href="replacedlink">click</a>
     </div>
</div>

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>
Share Improve this question asked Mar 17, 2017 at 9:40 parishparish 8562 gold badges19 silver badges32 bronze badges 2
  • 2 api.jquery.com/attr – Aleksandar Misich Commented Mar 17, 2017 at 9:41
  • http://stackoverflow.com/questions/2694640/find-an-element-in-dom-based-on-an-attribute-value – انجام پایان نامه مدیریت Commented Mar 17, 2017 at 9:46
Add a comment  | 

6 Answers 6

Reset to default 7

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>

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

Try This:

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

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.

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.

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

发布评论

评论列表(0)

  1. 暂无评论