从 CheerioJS DOM 对象中检索所有标签名称
Retrieve all tag names from CheerioJS DOM object
鉴于以下 HTML:
<html>
<head>
<title>This is text within the title tag</title>
</head>
<body>
This is text in the body tag
<br>
<h1>This is text in the h1 tag</h1>
<p>This is text in the p tag</p>
There is more text in the body after the p tag
</body>
</html>
我想使用 CheerioJS,一个 HTML 解析器,将每个 HTML 标签收集到一个数组中以进行操作。
所需的输出将是以下数组:
[html, head, title, /title, /head, body, br, h1, /h1, p, /p, /body, /html]
我一直在看 Cheerio's DOM object 但我不确定它是否是我需要的。
我认为您不需要为此使用外部库,您可以使用一个小函数自行 DOM。
const list = [];
function walkTheDOM(node, iteratee) {
iteratee(node);
node = node.firstChild;
while (node) {
walkTheDOM(node, iteratee);
node = node.nextSibling;
}
}
walkTheDOM(document.getElementsByTagName('html')[0], function (node) {
list.push(node)
});
console.log(list);
// [html, head, text, meta, ...]
这里是Fiddle.
你可以这样做:
$('*').get().map(el => el.name)
// [ 'html', 'head', 'title', 'body', 'br', 'h1', 'p' ]
请注意,结束标签不是离散节点,它们是开始标签所属节点的一部分。
鉴于以下 HTML:
<html>
<head>
<title>This is text within the title tag</title>
</head>
<body>
This is text in the body tag
<br>
<h1>This is text in the h1 tag</h1>
<p>This is text in the p tag</p>
There is more text in the body after the p tag
</body>
</html>
我想使用 CheerioJS,一个 HTML 解析器,将每个 HTML 标签收集到一个数组中以进行操作。
所需的输出将是以下数组:
[html, head, title, /title, /head, body, br, h1, /h1, p, /p, /body, /html]
我一直在看 Cheerio's DOM object 但我不确定它是否是我需要的。
我认为您不需要为此使用外部库,您可以使用一个小函数自行 DOM。
const list = [];
function walkTheDOM(node, iteratee) {
iteratee(node);
node = node.firstChild;
while (node) {
walkTheDOM(node, iteratee);
node = node.nextSibling;
}
}
walkTheDOM(document.getElementsByTagName('html')[0], function (node) {
list.push(node)
});
console.log(list);
// [html, head, text, meta, ...]
这里是Fiddle.
你可以这样做:
$('*').get().map(el => el.name)
// [ 'html', 'head', 'title', 'body', 'br', 'h1', 'p' ]
请注意,结束标签不是离散节点,它们是开始标签所属节点的一部分。