I’m trying to wrap all of the elements between two headings regardless of what they are without having to add classes. Example:
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function () {
$(".axxs-accordion > :header").addClass("h-trigger static").next().wrap("<div class='section collapsed'></div>");
});
</script>
<div class="axxs-accordion">
<h2>Section with a Paragraph</h2>
<!-- wrap here -->
<p>Here is some text content</p>
<!-- to here -->
<h2>Section with a Div and Mixed Content</h2>
<!-- wrap here -->
<h3>Heading</h3>
<p>Here is some content with text and a link.</p>
<p><a href="#" target="_blank">Test link</a></p>
<!-- to here -->
<h2>Section with a List</h2>
<!-- wrap here -->
<ul>
<li>List item 1</li>
<li>List item 2</li>
</ul>
<!-- to here -->
</div>
Obviously it works in the first and third sections, because there is only one element after the H2. But how do I wrap the group of elements in the second section? I’ve seen other posts about nextUntil, but those all of those examples had classes to work off of.
3
Answers
Actually, you do not need the class on h2 element:
To wrap all elements between two header elements with jQuery, you can use the following script. This will ensure that all elements between the headers are wrapped in a
<div>
with the classsection collapsed
.Explanation
h2
header and wraps all elements between this header and the nexth2
header in a<div>
with the classsection collapsed
.This script dynamically wraps all content between headers as specified.
Here’s an enhanced version with JavaScript to handle collapsing and expanding sections and CSS for styling:
Explanation
collapsed
class on the associated section, making it collapse or expand.This setup ensures that clicking on a header will collapse or expand the corresponding section content.