Change the layout. This is not possible / optimized for how your layout is executed.
First, the correct HTML name must begin with a letter.
Secondly, there can be only one identifier, without duplicates.
Thirdly, the space is not a valid character in the ID name.
Since your markup is invalid, here is a suggestion.
<div id="container"> <ul> <li data-showtime="19">7pm</li> <li data-showtime="20">8pm</li> <li data-showtime="21">9pm</li> </ul> <h6 class="time-title time-19" data-showtime="19">7pm</h6> <div class="show time-19">My TV Show 1</div> <div class="show time-19">My TV Show 2</div> <div class="show time-19">My TV Show 3</div> <div class="show time-19">My TV Show 4</div> <div class="show time-19">My TV Show 5</div> <h6 class="time-title time-20" data-showtime="20">8pm</h6> <div class="show time-20">My TV Show 5</div> <div class="show time-20">My TV Show 6</div> </div>
and script:
$(function() { showtime = {}; $("#container").find("h6.time-title").each(function() { var t = $(this); var d = t.data(); showtime[d.showtime] = {}; showtime[d.showtime]['caption'] = t.text(); var tempshows = []; $(".show.time-"+d.showtime).each(function() { showname = $(this).text(); tempshows.push(showname) }) showtime[d.showtime]['shows'] = tempshows; }) console.log(showtime); })
jsFiddle: http://jsfiddle.net/FhKAh/1/
If you cannot change the markup and you have to deal with it, try the following:
showtime = {}; $("h6").each(function() { h6 = $(this); var tempshow = []; h6.nextUntil("h6").each(function() { tempshow.push($(this).text()) }); showtime[h6.text()] = {}; showtime[h6.text()]['shows'] = tempshow; }); console.log(showtime);
jsFiddle: http://jsfiddle.net/CGyBK/
Aktee source share