學習筆記:DOM之appendChild

永遠的淨心發表於2020-10-22

appendChild

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>課時1</title>
    <style type="text/css">

    </style>
</head>  
<body>
    <ul id="list">

    </ul>
    <script type="text/javascript">
        var oUI = document.getElementById('list');
        var oFrag = document.createDocumentFragment();
        for(var i = 0; i < 10000; i++){
            var oLi = document.createElement('li');
            oLi.innerHTML = i + '、這是第' + i + '個專案';
            oLi.className = 'list-item';
            oFrag.appendChild(oLi);
        }
        oUI.appendChild(oFrag);
    </script>
</body>   
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>課時1</title>
</head>  
<body>
    <div>123</div>
    <p>234</p>
    
    <script type="text/javascript">
        var comment = document.createComment('我是註釋君');
        document.body.appendChild(comment);
        var div = document.getElementsByTagName('div')[0];
        var p = document.createElement('p');
        p.innerHTML = 'JavaScript';
        var text = document.createTextNode('ECMAScript');

        div.appendChild(p);
        div.appendChild(text);
        div.appendChild(comment);
        var a = document.getElementsByTagName('a')[0];
        var div = document.createElement('div');
        div.innerHTML = '<p>我是段落標籤</p>';

        document.body.appendChild(div);
        var newA = document.createElement('a');
        div.appendChild(newA);
        document.body.appendChild(div);
        div.appendChild(a);//剪下節點  
    </script>
</body>
</html>

childNodes

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>課時1</title>
</head>  
<body>
    <div>123</div>
    <script type="text/javascript">
        Text.prototype.aaa = 'aaa';
        CharacterData.prototype.bbb = 'bbb';
        var div = document.getElementsByTagName('div')[0];
        var text = div.childNodes[0];
        console.log(text.bbb);
    </script>
</body>
</html>

replaceChild

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>課時1</title>
    <style type="text/css">
        .title{
            color: orange;
        }
        .area{
            color: #666;
        }
    </style>
</head>  
<body>
    <ul id="list"></ul>
    <div>
        <h1></h1>
    </div>
    <script type="text/javascript">
      //parent.replaceChild(new,origin)
      var div = document.getElementsByTagName('div')[0];
      var h1 = document.getElementsByTagName('h1')[0];
      var h2 = document.createElement('h2');
      div.replaceChild(h2,h1);
    </script>
</body>
</html>

相關文章