jsday03節(jié)點

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;
    }
}

簡單的切換背景

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容