1、node类型:
js中所有节点类型都继承自Node类型,故所有节点类型都共享相同的基本属性和方法。每个节点都有一个nodeType属性,节点类型由在Node类型中定义的12个数值来表示。在这里需记住主要的三个:
Node.ELEMENT_NODE //1元素节点
Node.ATTRIBUTE_NODE //2属性节点
Node.TEXT_NODE //3文本节点
if(someNode.nodeType==1){
alert("该节点为元素节点。");
}
PS:遍历不同的节点:
window.onload=function(){
var box=document.getElementById('box');
for(var i=0;i<box.childNodes.length;i++){
if(box.childNodes[i].nodeType==1){
alert('元素节点:' + box.childNodes[i].nodeName);
}else if(box.childNodes[i].nodeType === 3){
alert('文本节点:' + box.childNodes[i].nodeValue);
}
}
}
2、nodeName与nodeValue:
<div id='box'></div>
window.onload=function(){
var box=document.getElementById('box');
alert(box.nodeName);//等价于box.tagName;
alert(box.node.Type);
alert(box.nodeValue);//null 元素节点本身没有内容
//node本身把及诶单指针放在<div></div>上,也就是说本身是没有Value的,只能获取当前节点的内容。
alert(box.innerHTML);//获取元素节点文本内容
}
box.innerHTML="测试<strong>pox</strong>"; //解析
box.childNodes[0].nodeValue="测试<strong>pox</strong>"; //不解析
3、节点之间的关系
childNodes:返回类型非数组,有length属性,可自行转换为数组,length属性是有生命的,可动态的查找当前长度。
var box=document.getElementById('box');
alert(box.childNodes); //非数组,返回当前元素节点的子节点
alert(box.childNodes.length);//动态返回当前时刻长度
alert(box.childNodes[0].nodeType); //文本节点对象,也可用item()方法访问具体节点
alert(box.childNodes.item(0));
(1)parentNode:用于获取当前节点元素的父节点,每个节点都有一个parentNode属性。
(2)previousSibiling与nextSibiling:获取当前节点的同胞节点,若无则返回null
(3)firstChild与lastChild:用于获取当前元素节点的第一个子节点和最后一个子节点,相当于:childNodes[0] 和childNodes[ someNode.childNodes.length-1]
(4)hasChildNodes():在当前节点包含一个或多个子节点的情况下返回true,否则返回false
( 5)ownerDocument:该属性返回该节点的文档对象根节点,返回的对象相当于document,并不常用。
4、空白节点的操作
(1)忽略空白:
function lostBlankNode(nodes){
var child=[];
for(var i=0;i<nodes.length;i++){
if(nodes[i].nodeType==3&&/^\s+$/.test(nodes[i].nodeValue)){
continue;}
child.push(nodes[i]);
}
return child;
}
//遍历box中的子节点(不包含空白节点)
window.onload=function(){
var box=document.getElementById('box');
alert(lostBlankNode(box.childNodes).length);
}
(2)删除空白
function deleteNode(nodes){
for (var i=0;i<nodes.length;i++){
if(nodes[i].nodeType==3&&/^\s+$/.test(nodes[i].nodeValue)){
//得到空白节点之后,移到父节点上,删除子节点
nodes[i].parentNode.removeChild(nodes[i]);
}
return nodes;
}
//调用方法同(1)
5、操作节点
(1)appendChild():在括号中所写的节点尾部添加,返回新节点
(2)createTextNode():创建文本节点(自动编码)
(3)insertBefore():有两个参数,即要插入的节点和作为参照的节点,创建到指定节点之前
(4)repalceChild():两个参数:要添加的节点与要替换的节点
(5)cloneNode():参数为布尔值,true为深复制,将复制节点及整个子节点树;false为浅复制,只复制该节点。PS:如要添加进文档中,需指定父节点
(6)removeChild():返回值为被移除的节点
(7)insertAfter():该方法可自己创建,可将新节点创建到指定节点之后:
function insertAfter(newNode,targetNode){
var parent=targetNode.parentNode;
if(parent.lastChild==targetNode){
parent.appendChild(newNode);
}else{
parent.insertBefore(newNode,targetNode.nextSibiling);}
}