英文:
Wrap every 2 elements in a <li> tag with js vanilla?
问题
const items = [...document.querySelectorAll('ul li')];
for (let i = 0; i < items.length; i += 2) {
const wrapper = document.createElement('div');
items.slice(i, i += 4);
items.parentNode.insertBefore(wrapper, items);
wrapper.appendChild(items);
}
英文:
I would like to put every two li elements into a div in vanilla js. But I don't know wher is problem.
Thnks for help!
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
const items = [...document.querySelectorAll('ul li')];
for (let i = 0; i < items.length; i += 2) {
const wrapper = document.createElement('div');
items.slice(i, i += 4);
items.parentNode.insertBefore(wrapper, items);
wrapper.appendChild(items);
}
答案1
得分: 1
你可以使用 document.createElement
在每次迭代中创建一个容器,然后将一些现有元素附加到它上面。
const container = document.getElementById('container');
const paragraphs = [...container.querySelectorAll('p')]; // 或者使用 container.children
let incr = 2;
for (let i = 0; i < paragraphs.length; i += incr) {
const div = document.createElement('div');
for (const p of paragraphs.slice(i, i + incr)) div.append(p);
container.append(div);
}
#container > div {
border: 1px solid;
}
<div id="container">
<p>文本</p>
<p>文本</p>
<p>文本</p>
<p>文本</p>
<p>文本</p>
<p>文本</p>
</div>
英文:
You can use document.createElement
to make a container on each iteration, then append some of the existing elements to it.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const container = document.getElementById('container');
const paragraphs = [...container.querySelectorAll('p')]; // or container.children
let incr = 2;
for (let i = 0; i < paragraphs.length; i += incr) {
const div = document.createElement('div');
for (const p of paragraphs.slice(i, i + incr)) div.append(p);
container.append(div);
}
<!-- language: lang-css -->
#container > div {
border: 1px solid;
}
<!-- language: lang-html -->
<div id="container">
<p>text</p>
<p>text</p>
<p>text</p>
<p>text</p>
<p>text</p>
<p>text</p>
</div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论