使用JavaScript包装一组DOM元素 [英] Wrapping a set of DOM elements using JavaScript
本文介绍了使用JavaScript包装一组DOM元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的页面上有一系列 p
标记,我想将它们全部包装到一个容器中,例如
I have a series of p
tags on my page and I want to wrap them all into a container, e.g.
<p>foo</p>
<p>bar</p>
<p>baz</p>
我想将所有上述标签包装到容器中,如下所示:
I want to wrap all the above tags into a container as follows:
<div>
<p>foo</p>
<p>bar</p>
<p>baz</p>
</div>
如何在元素中包装 NodeList
使用vanilla JavaScript?
How to wrap a NodeList
in an element using vanilla JavaScript?
推荐答案
你可以这样做:
// create the container div
var dv = document.createElement('div');
// get all divs
var divs = document.getElementsByTagName('div');
// get the body element
var body = document.getElementsByTagName('body')[0];
// apply class to container div
dv.setAttribute('class', 'container');
// find out all those divs having class C
for(var i = 0; i < divs.length; i++)
{
if (divs[i].getAttribute('class') === 'C')
{
// put the divs having class C inside container div
dv.appendChild(divs[i]);
}
}
// finally append the container div to body
body.appendChild(dv);
这篇关于使用JavaScript包装一组DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文