Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split content below every h3 with jQuery?

I have a peace of html that looks like this:

<h3>PETIT DEJEUNER</h3>
<p>FRANS ONTBIJT</p>
<p>CROISSANT</p>
<p>CROISSANT</p>

<h3>AUTRE PETIT DEJEUNER</h3>
<p>FRANS ONTBIJT</p>
<p>CROISSANT</p>
<p>CROISSANT</p>

<h3>AND ONE MORE DEJEUNER</h3>
<p>FRANS ONTBIJT</p>
<p>CROISSANT</p>
<p>CROISSANT</p>

Of course the contents vary. Unfortunately I do not control the html, it is delivered from another source. Can I split the content at every h3, creating a collection like this:

menu = [
    {
        title: 'PETIT DEJEUNER',
        contents: [<p contents>,<p contents>,<pcontents>]
    },
    {
        title: 'AUTRE PETIT DEJEUNER',
        contents: [<p contents>,<p contents>,<pcontents>]
    },
]

I'm using jQuery. Thanks!

like image 804
Jasper Kennis Avatar asked Dec 28 '22 17:12

Jasper Kennis


1 Answers

You can combine nextUntil() and filter() to match the paragraphs between <h3> elements, and use map() to build your arrays:

var menu = $("h3").map(function() {
    var $this = $(this);
    return {
        title: $this.text(),
        contents: $this.nextUntil("h3").filter("p").map(function() {
            return $(this).text();
        }).get();
    };
}).get();
like image 157
Frédéric Hamidi Avatar answered Dec 31 '22 03:12

Frédéric Hamidi