標籤:
一、innerText 屬性
<script type="text/javascript"> window.onload = function(){ var box = document.getElementById("box"); // alert(box.innerText);//擷取文本並過濾掉包含該文本的HTML標籤(直接刪除掉的)Firefox不支援 box.innerText=‘Mr.Lee‘;//設定值,替換掉原來有的文本 box.innerText=‘<strong>Mr.Lee</strong>‘;//Strong標籤不起作用,直接轉義為純文字 };</script></head><body> <div id="box"><p>測試Div</p></div></body>
除了 Firefox 之外,其他瀏覽器均支援這個方法。但 Firefox 的 DOM3 級提供了另外一個類似的屬性:textContent,做上相容即可通用。
<script> window.onload =function(){ var box = document.getElementById("box"); alert(box.textContent); };</script></head><body><div id="box"><p>測試Div</p></div></body>
做相容方案:
<script type="text/javascript"> window.onload = function(){ var box = document.getElementById("box"); alert(getInnerText(box)); setInnerText(box,"wodedfadf"); //相容方案 function getInnerText(element) { return (typeof element.textContent == ‘string‘) ? element.textContent : element.innerText; } function setInnerText(element, text) { if (typeof element.textContent == ‘string‘) { element.textContent = text; } else { element.innerText = text; } } };</script></head><body> <div id="box"><p>測試Div</p></div></body>
二、innerHTML 屬性
<script> window.onload =function(){ var box = document.getElementById("box"); alert(box.innerHTML); //擷取文本(不過濾 HTML標籤) box.innerHTML = ‘<b>123</b>‘; //可解析 HTML,結果文本加粗了; alert(box.innerHTML); };</script></head><body><div id="box"><p>測試Div</p></div></body>
雖然 innerHTML 可以插入 HTML,但本身還是有一定的限制,也就是所謂的範圍元素,離開這個範圍就無效了。
<script> window.onload =function(){ var box = document.getElementById("box"); box.innerHTML = "<script>alert(‘Lee‘);</script>"; //<script>元素不能被執行 box.innerHTML = "<style>background:red;</style>"; //<style>元素不能被執行 };</script></head><body><div id="box"><p>測試Div</p></div></body>
三、outerText
outerText 在取值的時候和 innerText 一樣,同時Firefox不支援,而賦值方法相當危險,他不單替換了常值內容,還將元素直接抹去。
<script> window.onload =function(){ var box = document.getElementById("box"); alert(box.outerText); box.outerText = ‘<b>123</b>‘; alert(box.outerText); alert(document.getElementById(‘box‘)); //null,建議不去使用 };</script></head><body><div id="box"><p>測試Div</p></div></body>
四、outerHTML
outerHTML 屬性在取值和 innerHTML 一致,但和 outerText 也一樣,很危險,賦值的之後會將元素抹去。
<script> window.onload =function(){ var box = document.getElementById("box"); box.outerHTML = ‘123‘; alert(document.getElementById(‘box‘)); //null,建議不去使用,Firefox舊版未抹去 };</script></head><body><div id="box"><p>測試Div</p></div></body>
JavaScript的DOM_操作內容