1. 程式人生 > >DOM 控制文本節點

DOM 控制文本節點

body 轉換成 data屬性 utf-8 div rac sub func 檢查

技術分享圖片

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>DOM控制文本節點</title>
</head>
<script type="text/javascript">
function processText(method){
var paraNode=document.getElementById("pId");
if(!paraNode.hasChildNodes())return; //檢查元素是否有子節點

var textNode=paraNode.firstChild;//獲取element 中的文本節點
if (textNode.nodeType==textNode.TEXT_NODE)//如果此接口類型為文本節點
{
switch(method){
case 0:
textNode.data=textNode.data.toUpperCase();
break;

case 1:
textNode.data=textNode.data.toLowerCase();
break;

case 2:
textNode.appendData("<_and>try you best to do it");
break;

case 3:
var preserveText=textNode.substringData(0,15);
textNode.replaceData(0,textNode.length-1,preserveText);
break;

case 4:
textNode.deleteData(0,textNode.length);
break;
}
}
else{
alert("沒有字符串");
}
}
</script>
<body>
<!--1.CharacterData.data屬性 CharacterData接口定義data 表示文本的內容
2.CharacterData.appendData()方法. CharacterData接口定義appendData()方法可以在文本末尾追加字符串
3.CharacterData.substringData(offset,count)方法,CharacterData定義substringData可以截取文本中的字符串
4.CharacterData.replaceData(offset, count,arg)方法,replaceData()定義可以替換文本內容
5.CharacterData.deleteData(offset,count),定義了刪除字符串
offset 表示刪除的起始位置,count表示刪除的字符數-->

<p id="pId">
Do not pray for an easy life ,pray for the strength to endure a difficle one
</p>
<input type="button" value="轉換成大寫" onclick="processText(0)" />
<input type="button" value="轉換成小寫" onclick="processText(1)" />
<input type="button" value="追加新字符" onclick="processText(2)" />
<input type="button" value="保留前十個字符" onclick="processText(3)" />
<input type="button" value="刪除全部文" onclick="processText(4)" />

<div id="divId"></div>


</body>
</html>

DOM 控制文本節點