JS添加 删除 修改节点

1.添加

<!DOCTYPE html>

<html>

<body>

<div id="div1">

<p id="p1">This is a paragraph.</p>

<p id="p2">This is another paragraph.</p>

</div>

<script>                       

//添加

var para=document.createElement("p");                     //创建新元素

var child=document.createTextNode("new Element"); //向新元素添加文本

para.appendChild(child);                                              //给元素追加文本

var place=document.getElementById("div1");              //找一个地方

place.appendChild(para);                                           //把元素加到这个地址上                                                               

</script>

</body>

</html>

2.添加到指定元素之前

<!DOCTYPE html>

<html>

<body>

<div id="div1">

<p id="p1">This is a paragraph.</p>

<p id="p2">This is another paragraph.</p>

</div>

<script>                       

 //添加到指定元素之前

var para=document.createElement("p");                     //创建新元素

var child=document.createTextNode("new Element"); //向新元素添加文本

para.appendChild(child);                                              //给元素追加文本

var place=document.getElementById("div1");               //找一个地方 

var kid=document.getElementById("p2");                      //确定在哪个元素前添加

place.insertBefore(para,child);                                      //加进去

</script>

</body>

</html>

3.删除

<!DOCTYPE html>

<html>

<body>

<div id="div1">

<p id="p1">This is a paragraph.</p>

<p id="p2">This is another paragraph.</p>

<a href="#" οnclick="return del( );">

</div>

<script>                       

//删除

var parent=document.getElementById("div1");      //找到父元素

var child=document.getElementById("p1")           //找到子元素

parent.removeChild(child);                                   //从父元素删去子元素

var child=document.getElementById("p1");          //删除的另外一种方法

child.parentNode.removeChild(child);

function del(){

if(confirm('确认要删除?'))

  {

    return true;

  }

    return false;

      }

</script>

</body>

</html>

4.修改

<!DOCTYPE html>

<html>

<body>

<div id="div1">

<p id="p1">This is a paragraph.</p>

<p id="p2">This is another paragraph.</p>

</div>

<script>

var para=document.createElement("p");                 

var child=document.createTextNode("new Element");

para.appendChild(child);

var place=document.getElementById("div1");

place.appendChild(para);

var parent=document.getElementById("div1");

var child=document.getElementById("p1")

parent.removeChild(child);

</script>

</body>

</html>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容