通过DOM解析获取所有的孩子和价值观 [英] Parsing through DOM get all children and values
问题描述
容器是一个div,我添加了一些基本的HTML。
Container is a div i've added some basic HTML to.
debug_log功能正在打印以下内容:
The debug_log function is printing the following:
我在跨度!
我在一个div!
我在一个
p
I'm in a span!
I'm in a div!
I'm in a
p
其余的文字发生了什么在p标签中(aragraph tag !!)。我想我不明白如何走遍文件树。我需要一个将解析整个文档树并返回所有元素及其值的函数。下面的代码是刚刚获取所有显示值的第一个破解。
What happened to the rest of the text in the p tag ("aragraph tag!!"). I think I don't understand how exactly to walk through the document tree. I need a function that will parse the entire document tree and return all of the elements and their values. The code below is sort of a first crack at just getting all of the values displayed.
container.innerHTML = '<span>I\'m in a span! </span><div> I\'m in a div! </div><p>I\'m in a <span>p</span>aragraph tag!!</p>';
DEMO.parse_dom(container);
DEMO.parse_dom = function(ele)
{
var child_arr = ele.childNodes;
for(var i = 0; i < child_arr.length; i++)
{
debug_log(child_arr[i].firstChild.nodeValue);
DEMO30.parse_dom(child_arr[i]);
}
}
推荐答案
当遍历DOM时,要指定起点。从那里,检查起点是否有 childNodes
。如果是这样,循环遍历它们并递归函数,如果它们也有 childNodes
。
Generally when traversing the DOM, you want to specify a start point. From there, check if the start point has childNodes
. If it does, loop through them and recurse the function if they too have childNodes
.
这里有一些输出的代码使用这些节点的DOM形式到控制台(我使用文档/ HTML元素作为起点)。如果允许非开发人员加载此页面/代码并使用 console ,则需要运行if
window.console
code>:
Here's some code that outputs to the console using the DOM form of these nodes (I used the document/HTML element as a start point). You'll need to run an if against window.console
if you're allowing non-developers to load this page/code and using console
:
recurseDomChildren(document.documentElement, true);
function recurseDomChildren(start, output)
{
var nodes;
if(start.childNodes)
{
nodes = start.childNodes;
loopNodeChildren(nodes, output);
}
}
function loopNodeChildren(nodes, output)
{
var node;
for(var i=0;i<nodes.length;i++)
{
node = nodes[i];
if(output)
{
outputNode(node);
}
if(node.childNodes)
{
recurseDomChildren(node, output);
}
}
}
function outputNode(node)
{
var whitespace = /^\s+$/g;
if(node.nodeType === 1)
{
console.log("element: " + node.tagName);
}else if(node.nodeType === 3)
{
//clear whitespace text nodes
node.data = node.data.replace(whitespace, "");
if(node.data)
{
console.log("text: " + node.data);
}
}
}
示例: http://jsfiddle.net/ee5X6/
这篇关于通过DOM解析获取所有的孩子和价值观的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!