首頁  >  文章  >  web前端  >  JavaScript動態改變HTML頁面元素例如新增或刪除_javascript技巧

JavaScript動態改變HTML頁面元素例如新增或刪除_javascript技巧

WBOY
WBOY原創
2016-05-16 16:40:091131瀏覽

可以透過JavaScript動態的改變HTML中的元素

在HTML中加入元素

首先需要建立一個標籤,然後在該標籤中新增對應的內容,然後將建立好的標籤新增到對應的位置。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 
<title>测试文档</title> 
<script type="text/javascript"> 
function add(){ 
var element = document.createElement("p"); 
var node = document.createTextNode("添加新段落"); 
element.appendChild(node); 
x = document.getElementById("demo"); 
x.appendChild(element); 
} 
</script> 
</head> 
<body> 
<div id="demo"> 
<p>这是第一段</p> 
</div> 
<input type="button" value="按钮" onclick="add()" /> 
</body> 
</html>

刪除HTML中的某個元素

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 
<title>测试文档</title> 
<script type="text/javascript"> 
function deleteE(){ 
var father = document.getElementById("demo"); 
var child = document.getElementById("p1"); 
father.removeChild(child); 
} 
</script> 
</head> 
<body> 
<div id="demo"> 
<p id="p1">这是第一段</p> 
<p id="p2">这是第二段</p> 
</div> 
<input type="button" value="删除" onclick="deleteE()" /> 
</body> 
</html>
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn