2016-08-30 69 views
0

我试图检查与JavaScript之间,如果两个html转义标记之间,存在一个div?看下面的例子:HTML源代码两个html标签之间的get元素被注释了吗?

<html> 
 
    <body> 
 
    <div>.....</div> 
 
    <h1>.....</h1> 
 
    <table> 
 
     <tr> 
 
     <td> 
 
      <!-- #html# --> 
 
      Get these Value 
 
      <!-- #/html# --> 
 
      <td> 
 
     </tr> 
 
    </table> 
 
    <!-- #html# --> 
 
      .... 
 
    <!-- #/html# --> 
 
    </body> 
 
</html>

+0

什么是你最终要完成?我试图弄清楚为什么要评论你的''标签。 –

+0

我昨天在这个例子中犯了一个错误。它们不是标签,但是它们与标签(#)嵌套,请参阅上面的示例。这些评论是由通讯系统制作的。如果这些评论里面有一个div标签,这意味着用户可以在仪表板上对其进行编辑。 – Perhp

回答

0

我使用ES6,但是你可以通过经典的迭代超过childNodes achive它。

var res = [], isInside = false; 
 

 
for (var node of document.body.childNodes) { 
 
    if (node.nodeType === Node.COMMENT_NODE) { 
 
    if (node.nodeValue.trim() === "<html>") { 
 
     isInside = true; 
 
     continue; 
 
    } else if (node.nodeValue.trim() === "</html>") { 
 
     break; 
 
    } 
 
    } 
 
    
 
    if (isInside) { // No else - include other comments 
 
    res.push(node); 
 
    } 
 
} 
 

 
console.log(res);
<!-- <html> --> 
 
    <div>...</div> 
 
<!-- </html> -->

+0

感谢您的帮助,这是我搜索的解决方案。通过一些修改,我可以将它用于我自己的代码。 – Perhp

+0

我现在有问题。如果元素位于文档主体的第一层,此方法效果很好,但如果它们嵌套到其他标记中,则无法获得这些评论。 (ps:他们的评论现在的值#html#请参阅上面的示例...) – Perhp

+0

@Perhp,使用递归dom遍历。 – Qwertiy