我们在写代码的时候可能会遇到类似的报错:
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. 获取节点有误
- 获取元素节点的方法拼写上有错误
- 如果获取节点返回的是一个数组,你可能会忘了要通过该数组的索引值获取到你想要的元素