Wrap some elements for an accordion in jquery

I currently have the following html:

<h3 />
<p />
<p />
<ul />
<ol />

<h3 />
<p />
<p />
<ul />
<ol />

<h3 />
<p />
<p />
<ul />
<ol />

I would like to create an accordion, but for this I need the following:

<h3 />
<div>
     <p />
     <p />
     <ul />
     <ol />
</div>

<h3 />
<div>
     <p />
     <p />
     <ul />
     <ol />
</div>

I tried the following, but it does not work:

$('.page2 .articleText p, .page2 .articleText ul').after('<div class="accordion">');
$('.page2 .articleText h4:not(:first)').before('</div>');

Any help is greatly appreciated.

Thank!

+3
source share
2 answers

You can use .nextUntil()and .wrapAll()to select and wrap each section, for example:

$("h3").each(function() {
    $(this).nextUntil("h3").wrapAll("<div />");
});​

Here you can see a working demo.

+1
source

Here's a quick dirty solution for packing a group of elements into a single div:

$(function(){
    var h  = $('h3');
    var p1 = $('h3 + p');
    var p2 = $('h3 + p + p');
    var ul = $('h3 + p + p + ul');
    var ol = $('h3 + p + p + ul + ol');

    h.each(function (i) {
        var group = $(p1[i]).add(p2[i]).add(ul[i]).add(ol[i]);
        var div = $('<div />').append(group);
        $(h[i]).after(div);
    });
});    

I believe that if you provided some interceptors, the code would be much simpler :)

0
source

Source: https://habr.com/ru/post/1734049/


All Articles