JSFiddle - React, Tailwind, and code Playground
HTML
<h1>
Test
</h1>
<p>
Test P
</p>
<table><td>data</td></table>
<h1>
Test 2
</h1>
<p>
2 p
</p>
<p>
3 p
</p>
<div>
Test div
</div>
<h1>
Test 3
</h1>
<p>
Test 3 Text
</p>
<h1><span lang=EN-GB style='font-family:"Verdana",sans-serif;color:#333333;
mso-ansi-language:EN-GB'><o:p> </o:p></span></h1>
CSS
.new {
background-color: blue;
}
.wrapper {
background-color: grey;
transition: all .25s ease-in-out;
height: auto;
}
.section-title {
background-color: grey;
}
.hide-wrapper {
opacity: 0;
height: 0;
transition: all .1s ease-in-out;
}
JavaScript
var nextUntil = function (elem, selector) {
var siblings = [];
elem = elem.nextElementSibling;
while (elem) {
if (elem.matches(selector)) break;
siblings.push(elem);
elem = elem.nextElementSibling;
}
return siblings;
};
var titleElements = document.querySelectorAll('h1');
console.log(titleElements.length);
titleElements.forEach(function (el, i) {
if (el.textContent.trim() !== '') {
el.className = 'section-title';
var container = document.createElement('div');
container.className = "wrapper";
container.id = i;
container.classList.add('hide-wrapper');
el.id = i;
var next = nextUntil(el, 'h1');
next.forEach(function(element) {
container.appendChild(element);
});
el.parentNode.insertBefore(container, el.nextSibling);
el.onclick = function(div) {
var specificWrapper = document.querySelector(".wrapper[id='" + div.target.id + "']");
console.log(specificWrapper);
if (specificWrapper.classList.contains('hide-wrapper')) {
specificWrapper.classList.remove('hide-wrapper');
} else {
specificWrapper.classList.add('hide-wrapper');
}
}
}
});