添加新句子

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<p>请自己定义并获取要求的内容</p>

<div id="div1">获取我并显示我的文字内容
    <div>中间的内容</div>
</div>
<div>
    <div id="div22" >获取这个div,并添加一个新的div到后面</div>
</div>
<div>
    <div id="div33" >获取这个div,并用一个新的div将它替换</div>
</div>
<div>
    <div id="div44" >获取这个div,并在它之前添加一个新的div</div>
</div>
<button onclick="test1()">第一个</button>
<button onclick="test2()">第二个</button>
<button onclick="test3()">第三个</button>
<button onclick="test4()">第四个</button>
<script>
    function test4(){
        var div4 = document.getElementById('div44');
        var pdiv4 = div4.parentNode;

        var div=document.createElement("div");
        var oText = document.createTextNode("新插入的4号地div元素");
        div.appendChild(oText);

        pdiv4.insertBefore(div, div4);
    }
    function test3(){
        var div3 = document.getElementById('div33');
        var pdiv3 = div3.parentNode;

        var div=document.createElement("div");
        var oText = document.createTextNode("我是新的第三号");
        div.appendChild(oText);

        pdiv3.replaceChild(div, div3);
    }
    function test2(){
        var ww=document.getElementById('div22');
        var pdiv = ww.parentNode;  // 找到付元素
//        alert(pdiv.innerHTML);

        var div=document.createElement("div");
        var oText = document.createTextNode("haha");
        div.appendChild(oText);
        // appendChild函数 将新的子元素添加到所有已经存在的子元素的末尾
//        document.body.appendChild(div);

        pdiv.appendChild(div);

    }
function test1() {
    var div1 = document.getElementById('div1');
//    div1.firstChild.nodeValue = '改变了内容';
    alert(div1.innerHTML);
//    alert(div1.innerText);
}
</script>
</body>
</html>

在div前后添加新句子

原文地址:https://www.cnblogs.com/zxy945/p/6524392.html