用普通Javascript将具有相同类的元素彼此相邻包装
正在寻找一种在包装器中使用相同类将元素相邻包装的方法。在jquery中很容易做到这一点,但我正努力在纯JS中找到一种方法。我能够删除.group之间的空标记,但不确定如何包装这些元素 当前HTML用普通Javascript将具有相同类的元素彼此相邻包装,javascript,Javascript,正在寻找一种在包装器中使用相同类将元素相邻包装的方法。在jquery中很容易做到这一点,但我正努力在纯JS中找到一种方法。我能够删除.group之间的空标记,但不确定如何包装这些元素 当前HTML <div class="group">1</div> <div class="group">2</div> <p><br /></p> <div class="
<div class="group">1</div>
<div class="group">2</div>
<p><br /></p>
<div class="group">3</div>
<p>Lorem ipsum dolor sit amet</p>
<section>
<div class="group">4</div>
<div class="group">5</div>
</section>
<p>Lorem ipsum dolor sit amet</p>
<div class="group">6</div>
我想我会一个接一个地做,我会在一个过程中删除“空白”段落,然后在另一个过程中分组(你可以在一个过程中完成所有工作,但这更复杂) 见内联评论:
//处理一个父级的函数
函数组子级(父级){
让孩子;
//首先删除“空白”段落
child=parent.firstElementChild;
while(儿童){
//首先抓住这个,因为我们可能会删除'child'`
const next=child.nextElementSibling;
如果(!child.classList.contains(“组”)){
//“Blank”表示它只有BR元素或空白文本节点
const remove=child.tagName==“P”和&Array.from(child.childNodes)。every(c=>
(c.nodeType===Node.TEXT\u Node&&!c.nodeValue)||
(c.tagName==“BR”)
);
如果(删除){
父母。removeChild(子女);
}
}
孩子=下一个;
}
//查找并分组。将段落分组
let组;
child=parent.firstElementChild;
while(儿童){
const next=child.nextElementSibling;
if(child.classList.contains(“组”)){
如果(!组){
//尚未创建组,请创建一个组并将其插入
组=document.createElement(“div”);
group.classList.add(“包装器”);
parent.insertBefore(组、子级);
}
//将其移动到当前组中
儿童组(child);
}否则{
//在这里分组
组=空;
}
孩子=下一个;
}
}
//处理所有`.group`元素;通常,晚些时候会发生
//在同一父级中处理早期的时已处理,因此请检查
for(数组.from(document.getElementsByClassName(“组”))的常量子级){
如果(!child.parentElement.classList.contains(“包装器”)){
groupChildren(child.parentElement);
}
}
1
2.
3.
Lorem ipsum dolor sit amet
4.
5.
Lorem ipsum dolor sit amet
6
以上所有组
元素都是同级元素。我们能假设这一定是真的吗?实际上不是真的,它不一定是兄弟姐妹。一些.group元素可以在另一个元素(div,section…)中,那么我们如何对它们进行分组呢?x
class=“group”>y..
的预期结果是什么?预期结果是x
和class=“group”>y好的,所以将它们分组在同一个父级中,但它们并不都有相同的父级。效果非常好!!!非常感谢。我一直在努力让这一切顺利进行。
<div class="wrapper">
<div class="group">1</div>
<div class="group">2</div>
<div class="group">3</div>
</div>
<p>Lorem ipsum dolor sit amet</p>
<section>
<div class="wrapper">
<div class="group">4</div>
<div class="group">5</div>
</div>
</section>
<p>Lorem ipsum dolor sit amet</p>
<div class="wrapper">
<div class="group">6</div>
</div>
// Create Wrapper
let wrapper = document.createElement('div');
wrapper.classList.add('wrapper');
// Add class to br parent
let brTags = document.querySelectorAll('br:first-child');
brTags.forEach(empty => {
empty.parentNode.classList.add('empty-paragraph');
});
// remove empty paragraphs between groups
const empty = document.querySelectorAll('.empty-paragraph');
empty.forEach(paragraph => {
if (paragraph.nextElementSibling.classList.contains('group') && paragraph.previousElementSibling.classList.contains('group')) {
paragraph.remove();
}
});