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

html - How to replace a specific href link using Javascript? - Stack Overflow

programmeradmin0浏览0评论

I'll try again with this as I'm not sure the last time I put a very clear question... I have a page that has a lot of linked images. I would like to change just one of the image links (it's the logo) using javascript. I can not directly edit the "body" html, but can put js in the "head" region.

Here is the html code:

<div id="ctl00">
  <h1 class="logo">
  <a href="" title="Menswear"><img src="/user/files/logo.png title="Menswear" alt="Menswear"></a>
  </h1>
</div>

and I want to change the html to:

<div id="ctl00">
    <h1 class="logo">
<a href="" title="Menswear"><img src="/user/files/logo.png title="Menswear" alt="Menswear"></a>
</h1>
</div>

Basically I want to remove the ".store" from the URL, but only this instance, not all URLs on the page.

I'll try again with this as I'm not sure the last time I put a very clear question... I have a page that has a lot of linked images. I would like to change just one of the image links (it's the logo) using javascript. I can not directly edit the "body" html, but can put js in the "head" region.

Here is the html code:

<div id="ctl00">
  <h1 class="logo">
  <a href="http://www.store.domain.co.nz" title="Menswear"><img src="/user/files/logo.png title="Menswear" alt="Menswear"></a>
  </h1>
</div>

and I want to change the html to:

<div id="ctl00">
    <h1 class="logo">
<a href="http://www.domain.co.nz" title="Menswear"><img src="/user/files/logo.png title="Menswear" alt="Menswear"></a>
</h1>
</div>

Basically I want to remove the ".store" from the URL, but only this instance, not all URLs on the page.

Share Improve this question edited Jul 23, 2015 at 0:13 Rookie asked Jun 30, 2015 at 3:47 RookieRookie 831 gold badge1 silver badge5 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 8

Check the DOM functions:

var x = document.getElementsByTagName("a")
for (i=0;i<x.length;++i) {
  if (x[i].getAttribute("href") == "http://www.this.link.co.nz") {
    x[i].setAttribute("href", "http://www.that.link.co.nz")
    x[i].setAttribute("title", "that link")
    x[i].replaceChild(
      document.createTextNode(
        "changed img:filename.jpg"
      ),
      x[i].firstChild
    )
  }
}
<p><a href="http://www.this.link.co.nz" title="this link">
    img:filename.jpg
</a>
</p>
<p><a href="http://www.this.link.co.nz" title="this link">
    img:filename.jpg
</a>
</p>

sets x to an array containing all a elements.

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

var a = document.querySelector('a[href="http://www.this.link.co.nz"]');
if (a) {
  a.setAttribute('href', 'http://www.that.link.co.nz')
}
<a href="http://www.this.link.co.nz" title="this link">
  <img src="/filename.jpg" />
</a>

发布评论

评论列表(0)

  1. 暂无评论