操作js中的dom
首先定义定义一个html页面,创建几个节点:
<div id = "father">
<h1>标题一</h1>
<p id = "p1">段落一</p>
<p class = "p2">段落二</p>
</div>
然后获取对应的节点信息:
<script>
var h1 = document.getElementsByTagName('h1');//通过标签名称
console.log(h1);
var p1 = document.getElementById('p1');//通过id
console.log(p1);
var p2 = document.getElementsByClassName('p2');//通过class
console.log(p2);
var father = document.getElementsByTagName('father');//获得父节点下的所有节点
var children = father.children;
</script>
接下来在定义一个html页面:
<div id = "id1">
</div>
我们先获取此div节点:
var id1 = document.getElementById('id1');
可以对这个节点的文本进行操作,值得注意的是innerHTML可以解析html样式,但是innerText不可以
id1.innerText = '124';
id1.innerHTML = '<strong>124</strong>';
可以对这个节点的css样式进行操作:
id1.style.color = 'red';
id1.style.fontSize = '200px';
id1.style.padding = '2em';
接下来我们来测试下删除节点操作,还是用上面的html
<div id = "father">
<h1>标题一</h1>
<p id = "p1">段落一</p>
<p class = "p2">段落二</p>
</div>
注意:删除dom树节点是先要获得需要删除节点的父节点,然后才能删除对应的dom节点信息,如下所示
var self = document.getElementById('p1');
var father = self.parentElement;
father.removeChild(self);
要注意的一个点就是,删除dom接点是一个动态的过程,以上面的例子为例,比如删除了h1节点,那么p1节点就变成了第一个节点了
father.removeChild(father.children[0]);