直接获取节点;操作节点属性
![](https://img2023.cnblogs.com/blog/2531222/202301/2531222-20230108001255952-1757395219.gif)
![](https://img2023.cnblogs.com/blog/2531222/202301/2531222-20230108001255952-1757395219.gif)
直接获取节点的几种方式
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
function fun1(){
// 获得document对象
var element1 =document.getElementById("d1");
console.log(element1);
element1.innerText="这是我的div";
}
function fun2(className){
var elements =document.getElementsByClassName(className);
console.log(elements)
for(var i =0;i<elements.length;i++){
console.log(elements[i])
}
}
function fun3(){
var elements =document.getElementsByTagName("input");
console.log(elements);
for(var i =0;i<elements.length;i++){
console.log(elements[i])
}
}
function fun4(){
var elements=document.getElementsByName("hobby");
console.log(elements);
for(var i =0;i<elements.length;i++){
console.log(elements[i])
}
}
</script>
</head>
<body>
<div id='d1' class="a">这是第一个div</div>
<div id='d2' class="a">这是第二个div</div>
<div id='d3' class="a">这是第三个div</div>
<input id='i1' class="a" name='name1'/>
<div id='d4' class="b" name='name1'>这是第四个div</div>
<div id='d5' class="b">这是第五个div</div>
爱好:
<input type="checkbox" name="hobby" value="1" />篮球
<input type="checkbox" name="hobby" value="2" />足球
<input type="checkbox" name="hobby" value="3" />羽毛球
<hr />
<input type="button" value="id值获取" onclick='fun1()' />
<input type="button" value="class属性值获取" onclick='fun2("b")' />
<input type="button" value="标签名获取" onclick='fun3()' />
<input type="button" value="name属性值获取" onclick='fun4()' />
</body>
</html>
![](https://img2023.cnblogs.com/blog/2531222/202301/2531222-20230108001255952-1757395219.gif)
![点击并拖拽以移动](https://img2023.cnblogs.com/blog/2531222/202301/2531222-20230108001255952-1757395219.gif)
操作节点属性
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
function fun1(){
//获得属性值
var node =document.getElementById("in1");
// 语法1 获得 节点.属性名 修改 节点.属性名 =属性值
console.log(node.type);
console.log(node.value);
//改变属性值
node.type="button";
node.value="你好我也好";
// 语法2 getAttribute setAttribute
console.log(node.getAttribute("type"));
console.log(node.getAttribute("value"));
node.setAttribute("type","button");
node.setAttribute("value","大家好");
}
</script>
</head>
<body>
<input type="text" value="你好呀" id="in1" />
<hr />
<input type="button" value="变" onclick="fun1()" />
</body>
</html>
![](https://img2023.cnblogs.com/blog/2531222/202301/2531222-20230108001255952-1757395219.gif)
![点击并拖拽以移动](https://img2023.cnblogs.com/blog/2531222/202301/2531222-20230108001255952-1757395219.gif)