admin管理员组文章数量:1323715
This question teaches how to get all TextNodes inside the document, and this is getting me the Javascript texts as well. What is the best way to filter out all the Nodes that are Javascript code?
This question teaches how to get all TextNodes inside the document, and this is getting me the Javascript texts as well. What is the best way to filter out all the Nodes that are Javascript code?
Share Improve this question asked May 12, 2016 at 5:35 lvellalvella 13.5k13 gold badges61 silver badges121 bronze badges2 Answers
Reset to default 14Text inside <script>
tags has only one thing in mon: their parent is a <script>
element.
if (node.parentNode.nodeName !== 'SCRIPT')
Another approach is to use the filter:
var rejectScriptTextFilter = {
acceptNode: function(node) {
if (node.parentNode.nodeName !== 'SCRIPT') {
return NodeFilter.FILTER_ACCEPT;
}
}
};
var walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_TEXT,
rejectScriptTextFilter,
false
);
var node;
var textNodes = [];
while(node = walker.nextNode()) {
textNodes.push(node.nodeValue);
}
console.log(textNodes);
<script> var str = "script here"; </script>
<p> text here </p>
You could clone the original document
, remove <script>
elements at cloned document
, then iterate remaining nodes of cloned document
本文标签: domUsing a TreeWalker to retrieve nonJavascript text nodesStack Overflow
版权声明:本文标题:dom - Using a TreeWalker to retrieve non-Javascript text nodes - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742125584a2421924.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论