我刚刚开始使用 Javascript,正在努力寻找一种方法:
- 查找一个或多个相同类型的连续元素,例如
<p>…</p>
或<p>…</p><p>…</p>
- 用新元素包围每个组,例如
<dd><p>…</p></dd>
或<dd><p>…</p><p>…</p></dd>
我还想限制脚本,使其仅适用于页面的特定部分,例如<div id="relevantbit"></div>
,但也许这可以算作一个单独的问题。
预先感谢您的帮助。
最佳答案
这是一个 native JavaScript 函数,它将在同一级别将连续标签包装在您想要包装的任何类型的标签中。它甚至可以递归工作,因此它可以找到任何级别的标签。如前所述,当检测连续标签时,它会忽略文本节点或注释节点等非元素,但如果这不是所需的行为(未指定详细信息),则可以轻松修改它。
您可以在此处查看工作演示:http://jsfiddle.net/jfriend00/Bp97p/ .
这是代码:
function wrapConsecutive(parent, desiredTagName, wrapTag) {
desiredTagName = desiredTagName.toUpperCase();
if (typeof parent === "string") {
parent = document.getElementById(parent);
}
function wrapNodes(nodeBegin, nodeEnd) {
// create and insert the wrap node
var wrapNode = document.createElement(wrapTag);
nodeBegin.parentNode.insertBefore(wrapNode, nodeBegin);
// now move the matched nodes into the wrap node
var node = nodeBegin, next;
while (node) {
next = node.nextSibling;
wrapNode.appendChild(node);
if (node === nodeEnd) {
break;
}
node = next;
}
}
function wrapChildren(parent) {
var next = parent.firstChild;
var firstInSeries = null;
var lastInSeries;
while (next) {
// only look at element nodes
if (next.nodeType === 1) {
wrapChildren(next);
if (next.tagName === desiredTagName) {
// found a matching tagName
// if we don't have a series yet, start one
// if we do have a series, just keep going
if (!firstInSeries) {
firstInSeries = next;
}
lastInSeries = next;
} else {
// did not find a matching tagName
// if we have a series, then end the series and process it
// if we didn't have a series yet, then keep looking for one
if (firstInSeries) {
// wrap from firstInSeries to next.previousSibling
wrapNodes(firstInSeries, lastInSeries);
firstInSeries = null;
}
}
}
next = next.nextSibling;
}
if (firstInSeries) {
wrapNodes(firstInSeries, lastInSeries);
}
}
wrapChildren(parent);
}
关于javascript - 使用 Javascript 查找元素组并将它们嵌套在新元素中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9594312/