报错:Uncaught TypeError: 获取的元素节点.setAttribute is not a function

没有检索到摘要

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们在写代码的时候可能会遇到类似的报错:
Uncaught TypeError: div1.setAttribute is not a function
源代码是这样的:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>设置属性值</title>
    <style>
        .red {
            width: 100px;
            height: 100px;
            background-color: red;
        }

        #yellow {
            width: 100px;
            height: 100px;
            background-color: yellow;
        }

        #blue {
            width: 100px;
            height: 100px;
            background-color: blue;
        }
    </style>

</head>
<body>
    <div name="one"></div>
    <div name="two" id="yellow"></div>

    <script>
        // 获取 name属性为one的 div
        var div1 = document.getElementsByName("one");
        // 给获取的div添加属性,由于在style里面设置了属性,所以该div会有宽高,会变成红色
        // 原来 name为one的div没有class属性,通过setAttribute(),给他设置了一个属性并赋值 
        // 相当于 <div name="one" class="red"></div>
        div1.setAttribute("class","red");
    </script>
</body>
</html>

报错的一行是

div1.setAttribute("class","red");

报错:Uncaught TypeError: div1.setAttribute is not a function
翻译:未捕获TypeError: div1。setAttribute不是一个函数
报错信息说setAttribute不是一个函数,可是setAttribute没有拼写错,setAttribute的参数都带引号了,为什么还是报错呢?
经过小编的一番努力,发现获取节点可能有误,于是写成了

var div1 = document.getElementsByName("one")[0];

这样写就对了

改正后的完整代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>设置属性值</title>
    <style>
        .red {
            width: 100px;
            height: 100px;
            background-color: red;
        }

        #yellow {
            width: 100px;
            height: 100px;
            background-color: yellow;
        }

        #blue {
            width: 100px;
            height: 100px;
            background-color: blue;
        }
    </style>

</head>
<body>
    <div name="one"></div>
    <div name="two" id="yellow"></div>

    <script>
        // 获取 name属性为one的 div
        var div1 = document.getElementsByName("one")[0];
        // 给获取的div添加属性,由于在style里面设置了属性,所以该div会有宽高,会变成红色
        // 原来 name为one的div没有class属性,通过setAttribute(),给他设置了一个属性并赋值 
        // 相当于 <div name="one" class="red"></div>
        div1.setAttribute("class","red");
    </script>
</body>
</html>

报错原因:
由于获取该元素的时候用的是getElementsByName(),得到的是数组,不是数组里面的元素,而我们要的不是数组,要的是元素。

总结:
当遇到 类似 获取的元素节点.操作元素节点的方法 is not a function 的错误的时候,大概是以下几个原因:

1. 操作节点的方法使用有误

  • 方法名拼错了
  • 方法的参数传错了,可能是没有加引号

2. 获取节点有误

  • 获取元素节点的方法拼写上有错误
  • 如果获取节点返回的是一个数组,你可能会忘了要通过该数组的索引值获取到你想要的元素
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值