【问题标题】:How to set the href of a link with no class or id?如何设置没有类或id的链接的href?
【发布时间】:2016-02-08 18:55:15
【问题描述】:

标题说明了一切;我正在尝试更改没有类或 ID 的链接。

例如,假设我有一个基本网站,其代码如下所示:

<!DOCTYPE html>
<html>
    <body>
        <div id="randomdiv">
            <a href="http://google.com">Google</a>
        </div>
        <a href="http://yahoo.com">Yahoo</a>
    </body>
</html>

我正在尝试将 google.com 链接更改为 stackoverflow.com。如您所见,链接没有 id 或类,但链接的父 div randomdiv 有一个 id。另外,页面上还有其他链接,所以我无法将更改应用到所有链接。

我试过了:

var d = document.getElementById("randomdiv");
d > a.href = "http://stackoverflow.com";

随机猜测。但这没有用。

有什么想法吗?谢谢。

【问题讨论】:

  • d &gt; a 是一种奇怪的语法。了解querySelector
  • 我试了一下作为猜测。我问是为了知道实际的语法。
  • 试试document.getElementById("randomdiv").getElementsByTagName('a')[0].href='http://stackoverflow.com';
  • 它是否始终是父元素中唯一的&lt;a&gt; 元素与id?或者它是否始终是您想要更改为“stackoverflow.com”的“google.com”链接?

标签: javascript html google-chrome google-chrome-extension


【解决方案1】:

WRThttp://www.w3schools.com/js/js_htmldom_elements.asp

你总是可以从一个元素中搜索一个元素。

var d = document.getElementById("randomdiv");
d. getElementsByTagName('a')[0].href = "http://stackoverflow.com";

【讨论】:

    【解决方案2】:

    使用querySelector 选择锚点

    document.querySelector("#randomdiv a").href = "http://www.example.com";
    

    【讨论】:

    • +1 我需要养成使用querySelector() 的习惯,而不是费尽心思。
    • 出于某种原因它说Uncaught TypeError: Cannot set property 'href' of null
    • 那么您是否要在元素呈现到页面之前找到它?
    • @epascarello 哦,是的,可能。 (哎呀。) 编辑:是的,我是。谢谢。把它作为答案,我会很高兴地把它标记为正确的。
    猜你喜欢
    • 2012-02-13
    • 1970-01-01
    • 2012-10-01
    • 2011-07-10
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多