获取DOM结点下的所有文本(原生版+jQuery)
<div>
<p>非度蝴蝶无路可走是想都别想村想都别想<em>非度蝴蝶无路可走是想都别想村想都别想</em></p>
</div>
<script type="text/javascript" src="./jquery-1.8b1.js"></script>
<script>
function getInnerText(el) {
if (typeof el == "string") return el;
if (typeof el == "undefined") { return el };
//如果el是DOM结点,除document
if (el.textContent) return el.textContent; // not needed but it is faster
if (el.innerText) return el.innerText; // IE doesn't have textContent
var str = "";
var cs = el.childNodes;
var l = cs.length;
for (var i = 0; i < l; i++) {
switch (cs[i].nodeType) {
case 1: //ELEMENT_NODE
str += getInnerText(cs[i]);
break;
case 3: //TEXT_NODE
str += cs[i].nodeValue;
break;
}
}
return str;
}
console.log(getInnerText(document.getElementById('content')));
console.log($('#content').text());
</script>
<div>
<p>非度蝴蝶无路可走是想都别想村想都别想<em>非度蝴蝶无路可走是想都别想村想都别想</em></p>
</div>
<script type="text/javascript" src="./jquery-1.8b1.js"></script>
<script>
function getInnerText(el) {
if (typeof el == "string") return el;
if (typeof el == "undefined") { return el };
//如果el是DOM结点,除document
if (el.textContent) return el.textContent; // not needed but it is faster
if (el.innerText) return el.innerText; // IE doesn't have textContent
var str = "";
var cs = el.childNodes;
var l = cs.length;
for (var i = 0; i < l; i++) {
switch (cs[i].nodeType) {
case 1: //ELEMENT_NODE
str += getInnerText(cs[i]);
break;
case 3: //TEXT_NODE
str += cs[i].nodeValue;
break;
}
}
return str;
}
console.log(getInnerText(document.getElementById('content')));
console.log($('#content').text());
</script>