How to split content below each h3 using jQuery?

I have an html world 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 content is changing. Unfortunately, I do not control html, it is delivered from another source. Can I split the content on each h3 by 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 am using jQuery. Thanks!

+4
source share
2 answers

You can combine nextUntil () and filter () to match paragraphs between <h3> elements and use map () to create 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(); 
+7
source
 var menu = []; $("<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>") .filter('h3') .each(function() { menu.push({ title: $(this).text(), contents: $(this).nextUntil('h3').map(function() { return $(this).text(); }).get() }); }); 
+3
source

All Articles