getElementsByTagName无法用于我的< a>标签 [英] getElementsByTagName doesn't work for my <a> tags

查看:59
本文介绍了getElementsByTagName无法用于我的< a>标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用它:

    <p>
        <a href="#">First</a>
        <a href="#" id="hasID">Second</a>
        <a href="#">Third</a>
        <a href="#" id="someID">Fourth</a>
    </p>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

    <script>
        var link = document.getElementsByTagName("a");
        link.style.fontSize = '16px';
        link.style.textDecoration = 'none';
        link.style.color = '#333333';
        link.style.fontWeight = 'bold';
    </script>

我正在尝试添加CSS样式( font-size 文本装饰颜色字体粗细)添加到我HTML代码的所有< a> 标签。

I'm trying to add CSS styles (font-size, text-decoration, color, font-weight) to all the <a> tags of my HTML code.

推荐答案

这不起作用,因为您尝试将更改与单个链接应用于列表。您需要遍历链接并将更改应用于单个项

This isn't working because you're trying to apply the changes to the list vs. the individual links. You need to loop through the links and apply the changes to the individual items

var all = document.getElementsByTagName("a");
for (var i = 0; i < all.length; i++) {
  var link = all[i];
  link.style.fontSize = '16px';
  link.style.textDecoration = 'none';
  link.style.color = '#333333';
  link.style.fontWeight = 'bold'
}

另外就像您的脚本在定义 a 元素之前运行。因此, getElementsByTagName 将返回一个空集合。尝试将脚本移动到定位元素的定义之后

Additionally it looks like your script is running before the a elements are defined. Hence the getElementsByTagName will return an empty collection. Try moving the script to after the definition of the anchor elements

这篇关于getElementsByTagName无法用于我的&lt; a&gt;标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆