Created
November 1, 2010 16:10
-
-
Save think49/658424 to your computer and use it in GitHub Desktop.
getTextNodeList.js : 対象のDOMノード及び子孫ノードからテキストノードを抽出して配列を返す
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
下記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