js中的DOM節點----文本節點


先看一段代碼:

<!DOCTYPE html>
<html>
<head>
    <title>文本節點</title>
</head>
<body>
    
    <ul id="list1">
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>

    <ul id="list2"><li>1</li><li>2</li><li>3</li></ul>

    <script type="text/javascript">
        var list1=document.getElementById('list1');
        var list2=document.getElementById('list2');

        console.log('list1子節點',list1.childNodes.length);
        console.log('list2子節點',list2.childNodes.length);
    </script>
</body>
</html>

上面的代碼是輸出list1和list2子節點個數,結果為:

為什么會出現子節點個數不一樣,就是因為存在文本節點,換句話說只要標簽之間存在內容(包括空格)就會有文本節點

寫個例子實現文本節點的增刪改

<!DOCTYPE html>
<html>
<head>
    <title>文本節點</title>
</head>
<body>

    <ul id="list1">
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>

    <button id="add">插入</button>
    <button id="replace">替換</button>
    <button id="remove">刪除</button>

    <script type="text/javascript">
        var lis=document.getElementsByTagName('li');
        var add=document.getElementById('add');
        var replace=document.getElementById('replace');
        var remove=document.getElementById('remove');


        //創建文本節點
        var text=document.createTextNode('Hello');

        function addText(){
            //給第一個li元素添加文本節點
            lis[0].appendChild(text)
        }
        function replaceText(){
            //替換第二個li元素文本節點
            lis[1].replaceChild(text,lis[1].firstChild)
        }
        function removeText(){
            //移除第三個li元素的文本節點
            lis[2].removeChild(lis[2].childNodes[0])
        }
        add.addEventListener('click',addText);
        replace.addEventListener('click',replaceText);
        remove.addEventListener('click',removeText);
        
    </script>
</body>
</html>

運行界面:

 

一般情況下每個元素只有一個文本子節點,有些情況下也可能包含多個文本子節點(例如創建多個文本節點並插入到同一元素中)。

 

normalize():將多個相鄰同胞文本節點合並成一個文本節點

splitText():將一個文本節點分割成兩個,傳入一個分割位置,原文本節點將包含從開始到指定位置之間的內容,新文本節點包含剩下的文本

實例代碼:

<!DOCTYPE html>
<html>
<head>
    <title>文本節點</title>
</head>
<body>
    <div id="text1"></div>
    <div id="text2"></div>
<script type="text/javascript">    
    var text1=document.getElementById('text1');
    var text2=document.getElementById('text2');
    var textNode1=document.createTextNode('Hello');
    var textNode2=document.createTextNode('World');
    var textNode3=document.createTextNode('Miss you');

//測試normalize()
    text1.appendChild(textNode1);
    text1.appendChild(textNode2);
    console.log('合並前文本節點個數:',text1.childNodes.length);
    text1.normalize();
    console.log('合並后文本節點個數:',text1.childNodes.length);


//測試splitText()
    text2.appendChild(textNode3)
    var newNode=text2.firstChild.splitText(4);
    console.log(text2.firstChild.nodeValue);
    console.log(newNode.nodeValue);
    console.log(text2.childNodes.length);
</script>
</body>
</html>

測試結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM