2016-10-31 26 views
0

我有代碼HTML:得到文本節點的所有HTML元素的自定義JavaScript對象

<html> 
<head></head> 
<body>myText 
<h1 id="a">Site 3</h1><h2>My Text</h2> 
<script src="index.js"></script> 
</body> 
</html> 

和我的Javascript代碼:

var el1 = document.childNodes[0] 
function get(node,ob) 
{ 
     ob = ob || {}; 

     if(node.childElementCount) 
     { 

      ob[node.nodeName] = {} 
      for(var x = 0; x < node.childNodes.length;x++) 
      { 
       if(node.childNodes[x].nodeType == 3) 
       { 

        console.log(node.childNodes[x])// if node is bode show corectly text "myText" 
        ob[node.nodeName]["text"] = node.childNodes[x]// but text non corectly why? 
        continue 
       } 
       get(node.childNodes[x],ob[node.nodeName])  
      }; 
     } 
     else 
     { 
      ob[node.nodeName] = (node.childNodes[0] == undefined ? null :node.childNodes[0].nodeValue) 
     } 
     return ob 
} 



var o = get(el1) 
console.log(o) 

當運行cosnole.log(O)一切都很好除了文本節點。我想在我的對象上得到文字,你能告訴我如何?

回答

0

呵呵呵我是天才; d; d

if(node.childElementCount) 
    { 

     ob[node.nodeName] = {} 
     ob[node.nodeName]["text"] = []; 
     for(var x = 0; x < node.childNodes.length;x++) 
     { 
      if(node.childNodes[x].nodeType == 3) 
      { 
       var txt = node.childNodes[x].nodeValue; 


       ob[node.nodeName]["text"].push(txt) 
       continue 
      } 
      get(node.childNodes[x],ob[node.nodeName])  
     }; 
    } 
相關問題