使用 Javascript 替换 HTML 中的 href 文本

replace href text in HTML using Javascript

是否可以使用Javascript将以下代码中的href值从href="http://**store**.mystitexxx.co.nz"更改为href="http://**www**.mystitexxx.co.nz"?它需要特定于此 DIV 或图像,即不是全局的

<div id="ctl00" class="hidden-xs">
   <h1 class="logo clearfix">
      <a href="http://store.mystorexxx.co.nz" title="My Store"><img class="img-responsive"src="/user/files/logo.png?t=1601271313" title="My Store" alt="My Store"/></a>
   </h1>
</div>

由于您需要它具体到这个 link,只需:

document.getElementById("link").href = "http://www.mystitexxx.co.nz";
<div id="ctl00" class="hidden-xs">
   <h1 class="logo clearfix">
      <a href="http://store.mystorexxx.co.nz" title="My Store" id="link"><img class="img-responsive"src="/user/files/logo.png?t=1601271313" title="My Store" alt="My Store"/></a>
   </h1>
</div>

与jQuery:

$("#link").attr("href", "http://www.mystitexxx.co.nz"); 

编辑:如果你没有控制权HTML添加一个ID。 (如果你这样做了,你为什么要用 Javascript 更改 href?:P)

document.querySelector("h1.logo a").href = "http://www.mystorexxx.co.nz";
//$("h1.logo a").attr("href", "http://www.mystitexxx.co.nz"); 
<div id="ctl00" class="hidden-xs">
   <h1 class="logo clearfix">
      <a href="http://store.mystorexxx.co.nz" title="My Store"><img class="img-responsive"src="/user/files/logo.png?t=1601271313" title="My Store" alt="My Store"/></a>
   </h1>
</div>

<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<style type="text/css">
    .selected{
        background-color : green;
    }
    </style>
<script>

    $(document).ready(function () {

        $('.logo a img.img-responsive').attr('src', "http://www.mystitexxx.co.nz")

    });
</script>
</head>
<body>
    <div id="ctl00" class="hidden-xs">
   <h1 class="logo clearfix">
      <a href="http://store.mystorexxx.co.nz" title="My Store"><img class="img-responsive"src="/user/files/logo.png?t=1601271313" title="My Store" alt="My Store"/></a>
   </h1>
</div>
</body>
</html>

哎呀,好像所有其他答案都相当复杂。

很简单:

jQuery('h1.logo a').attr('href', 'http://www.mystitexxx.co.nz');

或者,如果您不知道将它放在哪里/如何包含它,那么:

在您的 <head></head> 标签之间,添加:

<script>
    jQuery(function($) {
        $('h1.logo a').attr('href', 'http://www.mystitexxx.co.nz');
    }); 
</script>

而且,如果您还没有 jQuery 加载,那么只需像这样添加它(同样,在 <head> 标签之间):

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
    jQuery(function($) {
        $('h1.logo a').attr('href', 'http://www.mystitexxx.co.nz');
    }); 
</script>