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!
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With