操控 DOM 在下一章會講到使用選擇器,而本章最後講到有趣的取得文字的小技巧,使用物件類型 nodeType 判斷如果是文字就相加,如果 nodeType 是節點, 就使用遞迴的方法。
//jQuery 部分程式碼
function clone() {
var ret = this.map(function(){
if (!jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this)) {
var clone = this.cloneNode(true),
container = document.createElement("div");
container.appendChild(clone);
return jQuery.clean([container.innerHTML])[0];
} else {
return this.cloneNode(true);
}
});
var clone = ret.find("*").andSelf().each(function(){
if(this[expando] !== undefined) {
this[expando] = null;
}
})
return ret;
}
//jQuery 部分程式碼
function remove() {
jQuery("*", this).add([this]).each(function(){
jQuery.event.remove(this);
jQuery.removeData(this);
})
if(this.parentNode) {
this.parentNode.removeChild(this);
}
}
<div id="test"><b>Hello</b>, I'm a ninja!</div>
window.onload = function(){
var b = document.getElementById("test");
var text = b.textContent || b.innerText;
console.log(text === "Hello, I'm a ninja!")
if(typeof b.textContent !== "undefined") {
b.textContent = "Some new text"
} else {
b.innerText = "Some new text"
}
text = b.textContent || b.innerText;
console.log(text === "Some new text")
}
<div id="test"><b>Hello</b>, I'm a ninja!</div>
window.onload = function(){
var b = document.getElementById("test");
while (b.firstChild) {
b.removeChild(b.firstChild)
}
b.appendChild(document.createTextNode("Some new text"));
var text = b.textContent || b.innerText;
console.log(text === "Some new text")
}
<div id="test"><b>Hello <b>guys</b></b>, I'm a ninja!</div>
window.onload = function(){
function getText(elem) {
var text = "";
for(var i = 0; i < elem.childNodes.length; i++) {
var cur = elem.childNodes[i];
if(cur.nodeType === 3) {
text += cur.nodeValue;
} else if(cur.nodeType === 1) {
text += getText(cur);
}
}
return text;
}
var b = document.getElementById("test");
var text = getText(b);
console.log(text === "Hello guys, I'm a ninja!")
}
https://developer.mozilla.org/zh-TW/docs/Web/API/Node/nodeType
https://developer.mozilla.org/zh-TW/docs/Web/API/Element/innerHTML
https://developer.mozilla.org/zh-TW/docs/Web/API/Node/textContent
https://developer.mozilla.org/zh-TW/docs/Web/API/HTMLElement/innerText