2010-12-06 2 views

답변

2

다음은 당신에게 일치하는 요소 내에 포함 된 모든 텍스트 노드를 얻을 것이다 :

function getTextNodes(root, tagNamesArray) { 
    var textNodes = []; 
    var regex = new RegExp("^(" + tagNamesArray.join("|") + ")$", "i"); 
    var insideMatchingElement = false; 

    function getNodes(node, insideMatchingElement) { 
     if (node.nodeType == 3 && insideMatchingElement) { 
      textNodes.push(node); 
     } else if (node.nodeType == 1) { 
      var childrenInsideMatchingElement = insideMatchingElement || regex.test(node.nodeName); 
      for (var child = node.firstChild; child; child = child.nextSibling) { 
       getNodes(child, childrenInsideMatchingElement); 
      } 
     } 
    } 

    getNodes(root); 
    return textNodes; 
} 

var textNodes = getTextNodes(document.body, ["blockquote","em","h4","h6","p"]); 
+0

감사합니다. Tim ... 정확히 내가 필요한 것 .. :) –

0

사용 JQuery와

$('blockquote,em,h4,h6,p').each(function(i, v) { alert(v); }) 

UPDATE, 요소 텍스트 얻을 수

$('blockquote,em,h4,h6,p').each(function(i, v) { alert(v.text()); }) 
+0

반환 요소, 텍스트 노드가 아님 –

관련 문제