업데이트 :
1,000 회 이상 6 가지 방법 각각에 대한 몇 가지 기본 성능 테스트를 설명했습니다. getElementsByTagName가장 빠르지 만 모든 요소를 선택하지 않고 특정 유형의 태그 (내 생각에 p) 만 선택 하고 firstChild가 텍스트 요소 라고 맹목적으로 가정 하기 때문에 절반 수준의 작업을 수행합니다 . 결함이 거의 없을 수도 있지만 데모 목적으로 성능을 TreeWalker. 결과를 보려면 jsfiddle에서 직접 테스트를 실행하십시오 .
- TreeWalker 사용
- 사용자 지정 반복 순회
- 사용자 지정 재귀 순회
- Xpath 쿼리
- querySelectorAll
- getElementsByTagName
Text기본적으로 모든 노드 를 가져올 수있는 방법이 있다고 가정 해 보겠습니다 . node.nodeValueDOM 노드와 마찬가지로 실제 텍스트를 얻기 위해 각 결과 텍스트 노드를 탐색하고 호출 해야합니다. 따라서 성능 문제는 텍스트 노드를 반복하는 것이 아니라 텍스트가 아닌 모든 노드를 반복하고 유형을 확인하는 것입니다. 나는 (결과에 근거하여) TreeWalker속도가 빠르지는 getElementsByTagName않지만 (getElementsByTagName이 장애가있는 경우에도 ) 성능이 똑같이 빠르다고 주장 합니다 .
각 테스트를 1000 번 실행했습니다.
방법 총 ms 평균 ms
--------------------------------------------------
document.TreeWalker 301 0.301
반복 트래버 서 769 0.769
재귀 트래버 서 7352 7.352
XPath 쿼리 1849 1.849
querySelectorAll 1725 1.725
getElementsByTagName 212 0.212
각 방법의 출처 :
TreeWalker
function nativeTreeWalker() {
var walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_TEXT,
null,
false
);
var node;
var textNodes = [];
while(node = walker.nextNode()) {
textNodes.push(node.nodeValue);
}
}
재귀 트리 순회
function customRecursiveTreeWalker() {
var result = [];
(function findTextNodes(current) {
for(var i = 0; i < current.childNodes.length; i++) {
var child = current.childNodes[i];
if(child.nodeType == 3) {
result.push(child.nodeValue);
}
else {
findTextNodes(child);
}
}
})(document.body);
}
반복 트리 순회
function customIterativeTreeWalker() {
var result = [];
var root = document.body;
var node = root.childNodes[0];
while(node != null) {
if(node.nodeType == 3) {
result.push(node.nodeValue);
}
if(node.hasChildNodes()) {
node = node.firstChild;
}
else {
while(node.nextSibling == null && node != root) {
node = node.parentNode;
}
node = node.nextSibling;
}
}
}
querySelectorAll
function nativeSelector() {
var elements = document.querySelectorAll("body, body *");
var results = [];
var child;
for(var i = 0; i < elements.length; i++) {
child = elements[i].childNodes[0];
if(elements[i].hasChildNodes() && child.nodeType == 3) {
results.push(child.nodeValue);
}
}
}
getElementsByTagName (핸디캡)
function getElementsByTagName() {
var elements = document.getElementsByTagName("p");
var results = [];
for(var i = 0; i < elements.length; i++) {
results.push(elements[i].childNodes[0].nodeValue);
}
}
XPath
function xpathSelector() {
var xpathResult = document.evaluate(
"//*/text()",
document,
null,
XPathResult.ORDERED_NODE_ITERATOR_TYPE,
null
);
var results = [], res;
while(res = xpathResult.iterateNext()) {
results.push(res.nodeValue);
}
}
또한이 토론이 도움이 될 수 있습니다-http: //bytes.com/topic/javascript/answers/153239-how-do-i-get-elements-text-node