Finnegan Finnegan - 2 months ago 6
HTML Question

Wrapping a reoccuring collection of elements in a div

This is kind of a two part question - I have an HTML page where I need to take reoccurring groups of elements such as:

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


and wrap them individually with divs on each heading:

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


I know about getting elements by tag name, but I can't work out how to take the group of elements and then replacing them.

Thank you for any help.

Answer

You can use Array.from(), .forEach() loop to iterate h2 elements collection, check if .nextElementSibling .tagName is "P" in while loop, if true, push elements to an array.

Use .forEach() on array of arrays of p elements, create <div> element, append h2 at index of array to div element, loop each element of inner array, call .appendChild() with p element as parameter.

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>