我的页面上有一系列 p
标签,我想将它们全部包装到一个容器中,例如
<p>foo</p>
<p>bar</p>
<p>baz</p>
我想把上面所有的标签都包装成一个容器,如下所示:
<div>
<p>foo</p>
<p>bar</p>
<p>baz</p>
</div>
如何使用原生 JavaScript 将 NodeList
包装在元素中?
最佳答案
下面发布的是 jQuery 的 wrap
和 wrapAll
方法的纯 JavaScript 版本。我不能保证它们的工作方式与在 jQuery 中一样完全,但实际上它们的工作方式非常相似,应该能够完成相同的任务。它们使用单个 HTMLElement 或它们的数组。我没有测试确认,但它们应该都适用于所有现代浏览器(在一定程度上也适用于旧浏览器)。
与所选答案不同,这些方法通过使用 insertBefore 和 appendChild 来维护正确的 HTML 结构。
换行:
// Wrap an HTMLElement around each element in an HTMLElement array.
HTMLElement.prototype.wrap = function(elms) {
// Convert `elms` to an array, if necessary.
if (!elms.length) elms = [elms];
// Loops backwards to prevent having to clone the wrapper on the
// first element (see `child` below).
for (var i = elms.length - 1; i >= 0; i--) {
var child = (i > 0) ? this.cloneNode(true) : this;
var el = elms[i];
// Cache the current parent and sibling.
var parent = el.parentNode;
var sibling = el.nextSibling;
// Wrap the element (is automatically removed from its current
// parent).
child.appendChild(el);
// If the element had a sibling, insert the wrapper before
// the sibling to maintain the HTML structure; otherwise, just
// append it to the parent.
if (sibling) {
parent.insertBefore(child, sibling);
} else {
parent.appendChild(child);
}
}
};
查看 working demo在 jsFiddle 上。
wrapAll:
// Wrap an HTMLElement around another HTMLElement or an array of them.
HTMLElement.prototype.wrapAll = function(elms) {
var el = elms.length ? elms[0] : elms;
// Cache the current parent and sibling of the first element.
var parent = el.parentNode;
var sibling = el.nextSibling;
// Wrap the first element (is automatically removed from its
// current parent).
this.appendChild(el);
// Wrap all other elements (if applicable). Each element is
// automatically removed from its current parent and from the elms
// array.
while (elms.length) {
this.appendChild(elms[0]);
}
// If the first element had a sibling, insert the wrapper before the
// sibling to maintain the HTML structure; otherwise, just append it
// to the parent.
if (sibling) {
parent.insertBefore(this, sibling);
} else {
parent.appendChild(this);
}
};
查看 working demo在 jsFiddle 上。
关于javascript - 使用 JavaScript 包装一组 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3337587/