欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

HTML DOM - 元素

添加、刪除和替換 HTML 元素。

創(chuàng)建新的 HTML 元素 - appendChild()

如需向 HTML DOM 添加新元素,您首先必須創(chuàng)建該元素,然后把它追加到已有的元素上。

實例

<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 node=document.createTextNode("This is new.");
para.appendChild(node);

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

親自試一試

例子解釋

這段代碼創(chuàng)建了一個新的 <p> 元素:

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

如需向 <p> 元素添加文本,您首先必須創(chuàng)建文本節(jié)點。這段代碼創(chuàng)建文本節(jié)點:

var node=document.createTextNode("This is a new paragraph.");

然后您必須向 <p> 元素追加文本節(jié)點:

para.appendChild(node);

最后,您必須向已有元素追加這個新元素。

這段代碼查找到一個已有的元素:

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

這段代碼向這個已存在的元素追加新元素:

element.appendChild(para);

創(chuàng)建新的 HTML 元素 - insertBefore()

上一個例子中的 appendChild() 方法,將新元素作為父元素的最后一個子元素進行添加。

如果不希望如此,您可以使用 insertBefore() 方法:

實例

<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 node=document.createTextNode("This is new.");
para.appendChild(node);

var element=document.getElementById("div1");
var child=document.getElementById("p1");
element.insertBefore(para,child);
</script>

親自試一試

刪除已有的 HTML 元素

如需刪除 HTML 元素,您必須清楚該元素的父元素:

實例

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent=document.getElementById("div1");
var child=document.getElementById("p1");
parent.removeChild(child);
</script>

親自試一試

例子解釋

這個 HTML 文檔包含一個帶有兩個子節(jié)點(兩個 <p> 元素)的 <div> 元素:

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

查找 id="div1" 的元素:

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

查找 id="p1" 的 <p> 元素:

var child=document.getElementById("p1");

從父元素中刪除子元素:

parent.removeChild(child);

提示:能否在不引用父元素的情況下刪除某個元素?

很抱歉。DOM 需要了解您需要刪除的元素,以及它的父元素。

這里提供一個常用的解決方法:找到您需要刪除的子元素,然后使用 parentNode 屬性來查找其父元素:

var child=document.getElementById("p1");
child.parentNode.removeChild(child);

替換 HTML 元素

如需替換 HTML DOM 中的元素,請使用 replaceChild() 方法:

實例

<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 node=document.createTextNode("This is new.");
para.appendChild(node);

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

親自試一試