How to wrap global-text and button by creating a div.
<div >
<div > </div>
<div > </div>
<div > </div>
<div > </div>
</div>
CodePudding user response:
Create an element and append it to the place you want it. Select the elements you want to be in that element and append them to that new div.
//Select the elements you want inside
const divs = document.querySelectorAll(".global-button, .global-text");
// create the div to wrap your elements
const wrapper = document.createElement("div");
// add it to the DOM
divs[0].before(wrapper);
// insert the elements into the newly created div
divs.forEach(div => wrapper.append(div));
div {
padding: 2em;
margin: .4em;
border: 1px solid black;
min-height: 2em;
}
<div >
<div >a</div>
<div >b</div>
<div >c</div>
<div >d</div>
</div>
If you have multiple of these, you need to do it slightly different
function wrapIt(parentElem, selectors) {
//Select the elements you want inside
const divs = parentElem.querySelectorAll(selectors);
// create the div to wrap your elements
const wrapper = document.createElement("div");
// add it to the DOM
divs[0].before(wrapper);
// insert the elements into the newly created div
divs.forEach(div => wrapper.append(div));
}
var contents = document.querySelectorAll(".content");
contents.forEach((content) => wrapIt(content, ".global-button, .global-text"));
div {
padding: 2em;
margin: .4em;
border: 1px solid black;
min-height: 2em;
}
<div >
<div >a</div>
<div >b</div>
<div >c</div>
<div >d</div>
</div>
<div >
<div >a</div>
<div >b</div>
<div >c</div>
<div >d</div>
</div>
<div >
<div >a</div>
<div >b</div>
<div >c</div>
<div >d</div>
</div>