Skip to content

Instantly share code, notes, and snippets.

@think49
Created November 1, 2010 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save think49/658424 to your computer and use it in GitHub Desktop.
Save think49/658424 to your computer and use it in GitHub Desktop.
getTextNodeList.js : 対象のDOMノード及び子孫ノードからテキストノードを抽出して配列を返す
/**
* getTextNodeList.js
*
* @version 1.1.7
* @author think49
* @url https://gist.github.com/658424
*/
var getTextNodeList = (function () {
// define DOM Interface Object "Node" (for IE)
var Node = (typeof Node === 'function' || typeof Node === 'object' && Node) ? Node : (function () {
function Node () { ; }
// define Function#name
if (!('name' in Node)) {
Node.name = 'Node';
}
// define nodeType literal
Node.ELEMENT_NODE = 1;
Node.ATTRIBUTE_NODE = 2;
Node.TEXT_NODE = 3;
Node.CDATA_SECTION_NODE = 4;
Node.ENTITY_REFERENCE_NODE = 5;
Node.ENTITY_NODE = 6;
Node.PROCESSING_INSTRUCTION_NODE = 7;
Node.COMMENT_NODE = 8;
Node.DOCUMENT_NODE = 9;
Node.DOCUMENT_TYPE_NODE = 10;
Node.DOCUMENT_FRAGMENT_NODE = 11;
// define Function#toString
Node.toString = function () { return 'function Node() { [custom code] }'; };
return Node;
})();
function getTextNodeList (contextNode) {
var ELEMENT_NODE, DOCUMENT_NODE, DOCUMENT_FRAGMENT_NODE, TEXT_NODE, textNodeList, targetNode, i, l;
if (typeof contextNode !== 'object') {
throw new TypeError(contextNode + ' is not a object');
}
ELEMENT_NODE = Node.ELEMENT_NODE;
DOCUMENT_NODE = Node.DOCUMENT_NODE;
DOCUMENT_FRAGMENT_NODE = Node.DOCUMENT_FRAGMENT_NODE;
TEXT_NODE = Node.TEXT_NODE;
textNodeList = [];
if ('length' in contextNode && 'item' in contextNode) {
for (i = 0, l = contextNode.length; i < l; i++) {
targetNode = contextNode[i];
switch (targetNode.nodeType) {
case ELEMENT_NODE:
case DOCUMENT_NODE:
case DOCUMENT_FRAGMENT_NODE:
textNodeList = textNodeList.concat(getTextNodeList(targetNode.childNodes));
break;
case TEXT_NODE:
textNodeList.push(targetNode);
break;
}
}
} else {
switch (contextNode.nodeType) {
case ELEMENT_NODE:
case DOCUMENT_NODE:
case DOCUMENT_FRAGMENT_NODE:
textNodeList = textNodeList.concat(getTextNodeList(contextNode.childNodes));
break;
case TEXT_NODE:
textNodeList.push(contextNode);
break;
}
}
return textNodeList;
}
return getTextNodeList;
})();
@think49
Copy link
Author

think49 commented Nov 2, 2010

下記URLで解説しています。

getTextNodeList.js
http://vird2002.s8.xrea.com/javascript/getTextNodeList.html


U D ◆TPP2IbCBBq さんにアドバイスをいただきました。

掲示板/JavaScript質問板/document.body の子孫テキストノードを配列で取得 - TAG index Webサイト
http://www.tagindex.com/cgi-lib/q4bbs/patio.cgi?mode=view&no=2724

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment