我有一系列p
我页面上的标签,我想将它们全部包装到一个容器中,例如
<p>foo</p>
<p>bar</p>
<p>baz</p>
我想将以上所有标签包装到一个容器中,如下所示:
<div>
<p>foo</p>
<p>bar</p>
<p>baz</p>
</div>
如何包裹一个NodeList
在使用普通 JavaScript 的元素中?
下面发布的是 jQuery 的纯 JavaScript 版本wrap
and wrapAll
方法。我不能保证它们有效exactly就像它们在 jQuery 中一样,但实际上它们的工作方式非常相似,并且应该能够完成相同的任务。它们可以使用单个 HTMLElement 或它们的数组。我还没有进行测试来确认,但它们应该都可以在所有现代浏览器中工作(以及在一定程度上较旧的浏览器)。
与选定的答案不同,这些方法通过使用 insertBefore 以及appendChild 来维护正确的 HTML 结构。
wrap:
// 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);
}
}
};
See a 工作演示在 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);
}
};
See a 工作演示在 jsFiddle 上。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)