DOM操作——怎样添加、移除、移动、复制、创建和查找节点

(1)创建新节点

      createDocumentFragment()    //创建一个DOM片段

      createElement()   //创建一个具体的元素

      createTextNode()   //创建一个文本节点

(2)添加、移除、替换、插入、复制

      appendChild()

      removeChild()

      replaceChild()

      insertBefore()

  cloneNode()

(3)查找

      getElementsByTagName()    //通过标签名称

      getElementsByName()    //通过元素的Name属性的值

      getElementById()    //通过元素Id,唯一性

 

appendChild()

<div id="div1">
<p id="p1">这是一个段落。</p>
<p id="p2">这是另一个段落。</p>
</div>

<script>
var para=document.createElement("p");
var node=document.createTextNode("这是新段落。");
para.appendChild(node);

var element=document.getElementById("div1");
element.appendChild(para);
</script>

removeChild()

<div id="div1">
<p id="p1">这是一个段落。</p>
<p id="p2">这是另一个段落。</p>
</div>

<script>
var parent=document.getElementById("div1");
var child=document.getElementById("p1");
parent.removeChild(child);
</script>

replaceChild()

<ul id="myList"><li>Coffee</li><li>Tea</li><li>Milk</li></ul>

<p id="demo">点击按钮来替换列表中的首个项目。</p>

<button onclick="myFunction()">试一下</button>

<script>
function myFunction()
{
var textnode=document.createTextNode("Water");
var item=document.getElementById("myList").childNodes[0];
item.replaceChild(textnode,item.childNodes[0]);
}
</script>

insertBefore()

<ul id="myList"><li>Coffee</li><li>Tea</li></ul>

<p id="demo">请点击按钮向列表插入一个项目。</p>

<button onclick="myFunction()">试一下</button>

<script>
function myFunction()
{
var newItem=document.createElement("LI")
var textnode=document.createTextNode("Water")
newItem.appendChild(textnode)

var list=document.getElementById("myList")
list.insertBefore(newItem,list.childNodes[0]);
}
</script>

cloneNode()

<ul id="myList1"><li>Coffee</li><li>Tea</li></ul>
<ul id="myList2"><li>Water</li><li>Milk</li></ul>

<p id="demo">请点击按钮把项目从一个列表复制到另一个列表中。</p>

<button onclick="myFunction()">试一下</button>

<script>
function myFunction()
{
var itm=document.getElementById("myList2").lastChild;
var cln=itm.cloneNode(true);//如果您需要克隆所有后代,请把 deep 参数设置 true,否则设置为 false。
document.getElementById("myList1").appendChild(cln);
}
</script>

 


用.firstChild   在现代浏览器下,比如Chrome,FF,ie11等等,由于会把<div>   <p>两个标签之间的空白节点也解析出来,所以会alert出#text(由于空白节点是属于text文本节点)

如果把html的Demo改成如下,则无论在古老浏览器还是现代浏览器中得到的结果都是一样:

<div><p>123</p></div>
可以用children方法

<div>
    <p>123</p>
</div>
var first=document.getElementByTagName("div")[0].children[0]

posted on 2018-01-31 16:57  bbqwwb  阅读(260)  评论(0编辑  收藏  举报

导航