第三天:JavaScript的DOM对象和DOM操作HTML

1. DOM操作HTML

1)注意:绝对不要在文档加载完成之后使用docment.write()。这样会覆盖原来的文档

<body>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>

<button onclick="aaa()">按钮</button>

</body>
<script>
function aaa(){
document.write("world");
}
</script>

运行结果:

2)寻找元素:

通过id寻找html元素

<body>
<p id="pid">hello</p>
<button onclick="demo()">按钮</button>

</body>
<script>
function demo(){
var nv=document.getElementById("pid").innerHTML="ws"; //获得id

 nv.innerHTML="world"; //通过innerHTML改变html内容
}
</script>

通过标签名寻找html元素

document.getElementsByTagName("p") 


修改属性

1)修改链接地址:修改属性href
<body>
<a id="aid" href="http://www.baidu.com">hello</a>


<button onclick="demo()">按钮</button>

</body>
<script>
function demo(){
document.getElementById("aid").href="http://mail.163.com";

}
</script>

2)修改图片,属性src
<body>
<img id="iid" src="0.png">
<button onclick="demo()">按钮</button>
</body>
<script>
function demo(){
document.getElementById("iid").src="1.png";
}
</script>
我容易犯的错误,赋值后面忘记加双引号, 未通过id关联,未通过函数关联







问题:不会用

  通过标签名寻找html元素

document.getElementsByTagName("p") 

原文地址:https://www.cnblogs.com/fenr9/p/5567301.html