我们先来了解一下JavaScript对DOM节点是如何进行创建、添加、删除、插入、查找、复制、替换的。
//创建
document.createElement(); //创建一个元素
document.createTextNode(); //创建一个文本节点
//添加
appendChild(node); //在末尾添加元素
//删除
removeChild(node); //移除节点
//插入
insertBefore(node, node1); //在节点node1之前插入元素
//查找
document.getElementById(); //按id查找
document.getElementsByTagName(); //按标签名查找
document.getElementsByName(); //按元素的name属性查找
document.getElementsByClassName(); //按类名查找
//复制
cloneNode(true); //复制该元素及后代的元素内容
cloneNode(false); //只复制节点本身
//替换
replaceChild(newnode, oldnode); //替换节点
好,那么接下来我们来写几个例子来看看具体是怎么实现的
appendChild()实例
<!DOCTYPE HTML>
<html>
<body>
<ul id="firstnode">
<li>hello</li>
</ul>
<button onclick="myfunction()">点击添加</button>
<script>
function myfunction(){
var node = document.createElement("li");
var text = document.createTextNode("world");
node.appendChild(text);
document.getElementById("firstnode").appendChild(node);
}
</script>
</body>
</html>
已知id为text的input输入框,希望获得输入框中输入的值
document.getElementById("text").value;
获取页面中所以checkbox
var List = document.getElementByTagName("input");
var checkBoxList = [];
var len = List.length;
while( len-- ) {
if( List[len].type == "checkbox" ) {
checkBoxList.push(List[len]);
}
}
设置一个id为test的div的html内容为hello world,字体颜色设置为黑色
var node = document.getElementById("test");
node.innerHTML = "hello world";
node.style.color = "#000";
自此,我们简单的了解了原生JavaScript对DOM的基本操作。