gpt4 book ai didi

javascript - 在 div 中包装重复出现的元素集合

转载 作者:行者123 更新时间:2023-11-28 01:06:25 30 4
gpt4 key购买 nike

这是一个分为两部分的问题 - 我有一个 HTML 页面,我需要在其中获取重复出现的元素组,例如:

<h2>1</h2>
<p>foo</p>
<p>bar</p>
<h2>2</h2>
<p>fizz</p>

并在每个标题上用 div 单独包装它们:

<div>
<h2>1</h2>
<p>foo</p>
<p>bar</p>
</div>
<div>
<h2>2</h2>
<p>fizz</p>
</div>

我知道如何通过标签名称获取元素,但我不知道如何获取元素组然后替换它们。

感谢您的帮助。

最佳答案

您可以使用 Array.from() , .forEach()循环迭代 h2元素集合,检查是否.nextElementSibling .tagName"P"while循环,如果 true , 将元素推送到数组。

使用 .forEach()p 的数组数组上元素,创建 <div>元素,追加 h2index数组到 div元素,循环内部数组的每个元素,调用.appendChild()p元素作为参数。

var headers = document.querySelectorAll("h2");
var arr = [];

Array.from(headers).forEach(function(h2, index) {
arr[index] = [];
var curr = h2.nextElementSibling;
while (curr.tagName === "P") {
arr[index].push(curr);
var next = curr.nextElementSibling;
curr = next;
}
});

arr.forEach(function(html, index) {
var div = document.createElement("div");
document.body.appendChild(div);
div.appendChild(headers[index]);
html.forEach(function(el) {
div.appendChild(el)
})
});
div {
padding: 4px;
margin: 4px;
border: 2px solid green;
}
<h2>1</h2>
<p>foo</p>
<p>bar</p>
<h2>2</h2>
<p>fizz</p>

关于javascript - 在 div 中包装重复出现的元素集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39553860/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com