1.创建元素 插入元素
①创建元素节点 createElement()
②创建文本节点 createTextNode()
③把新的节点添加到子节点,也可以把文本节点添加到空节点中 appendChild()
④删除子节点 removeChild()
⑤在指定的子节点前面插入新的子节点。 insertBefore()
let box = document.getElementById('box');
let a = document.createElement('section'); //创建一个元素节点,内容为空 <section></section>
let b = document.createTextNode('Kolento'); //创建一个文本节点 Kolento
a.appendChild(b); //把b的内容放入a节点中 <section>Kolento</section>
//此时如果需要把a节点插入 id=box 节点中
box.appendChild(a);
box.insertBefore(a,box.childNodes[0]); //在第1个子节点前插入节点
//结果如下
<div id="box">
<section>Kolento</section>
</div>
box.childNodes; //返回数组 box下的子节点集
box.removeChild(box.childNodes[0]) //删除第一个子节点
2.创建,修改,获取元素属性
\let box = document.getElementById('box');
box.setAttribute('test','yes'); //创建属性
box.setAttribute('test','no'); //修改属性
box.getAttribute('test'); //获取属性 no
网友评论