一
html
<div id="dv">
<p>我是p</p>
<span>我是span</span>
<ul id="list">
<li>01</li>
<li>02</li>
<li id="three">03</li>
<li>04</li>
<li>05</li>
<li>06</li>
</ul>
</div>
js 節(jié)點 1是標(biāo)簽 2是屬性 3是文本
function $(id){
return document.getElementById(id);
}
console.log($("list").parentNode);//得到父節(jié)點
console.log($("list").parentElement)//得到父元素
console.log($("list").parentNode.nodeType)//標(biāo)簽的----1(屬性)
console.log($("list").parentNode.nodeName)//標(biāo)簽的----大寫的名字
console.log($("list").parentNode.nodeValue)//標(biāo)簽的---null(文本內(nèi)容)
console.log($("list").childNodes);//得到子節(jié)點(在ie8中得到的是子元素)
console.log($("list").children);//得到子元素(ie8不支持)
console.log($("list").firstChild);//第一個子節(jié)點(在ie8中得到的是子元素)
console.log($("list").firstElementChild);//第一個子元素(ie8不支持)
console.log($("list").lastChild);//最后一個節(jié)點(在ie8中得到的是子元素)
console.log($("list").lastElementChild);//最后一個子節(jié)點(ie8不支持)
console.log($("list").getAttributeNode("id"))//獲取屬性節(jié)點
console.log($("three").previousSibling);//前一個兄弟節(jié)點
console.log($("three").previousElementSibling);//前一個兄弟元素
console.log($("three").nextSibling);//下一個兄弟節(jié)點
console.log($("three").nextElementSibling);//下一個兄弟元素
小結(jié):在標(biāo)準(zhǔn)瀏覽器中獲取節(jié)點都是對應(yīng)的節(jié)點,獲取的元素都是對應(yīng)的元素。
在ie8中獲取的節(jié)點都是元素,獲取的元素都是undefined,不支持元素代碼
二
獲得任意元素的第一個子元素和最后一個子元素
//獲得任意元素的第一個子元素
function getFirstElemenChild(element){
if(element.firstElementChild){
return element.firstElementChild;
}else{
var node=element.firstChild;
while(node && node.nodeType != 1){
node=node.nextSibling;
}
return node;
}
}
//獲得任意元素的最后一個子節(jié)點
function getLastElementChild(element){
if(element.firstElementChild){
return element.firstElementChild;
}else{
var node=element.firstChild;
while(node && node.nodeType != 1){
node=node.previousSibling;
}
return node;
}
}