I'm building a dynamic summary generator with jQuery. I want to list all H2 and H3 on the page.
I did it for H2, this is my code:
EDIT: I just update my code, including H2 and H3 but there are few errors.
<div id="summary"></div>
<script>
var counter = 0;
$('h2').each(function() {
counter++;
$(this).attr("id", "title-" + counter);
$('#summary').append('<a href="#title-' + counter + '" class="summary-link">' + $(this).text() + '</a>');
//
var counter_2 = 0;
$('h2 ~ h3').each(function() {
counter_2++;
$(this).filter(function() {
return $(this).nextAll('h2').length
}).attr("id", "subtitle-" + counter_2);
$('#summary').append('<a href="#subtitle-' + counter_2 + '" class="summary-link">' + $(this).text() + '</a>');
});
});
</script>
Blog post example:
<h2>Post title 1</h2>
<h3>Post subtitle 1</h3>
<h3>Post subtitle 2</h3>
<h2>Post title 2</h2>
<h3>Post subtitle 3</h3>
<h3>Post subtitle 4</h3>
My code results:
<h2 id="title-1">Post title 1</h2>
<h3 id="subtitle-1">Post subtitle 1</h3>
<h3 id="subtitle-2">Post subtitle 2</h3>
<h2 id="title-2">Post title 2</h2>
<h3 id="subtitle-3">Post subtitle 3</h3>
<h3 id="subtitle-4">Post subtitle 4</h3>
<a href="#title-1">Post title 1</a>
<a href="#subtitle-1">Post subtitle 1</a>
<a href="#subtitle-2">Post subtitle 2</a>
<a href="#subtitle-3">Post subtitle 3</a>
<a href="#subtitle-4">Post subtitle 4</a>
<a href="#title-2">Post title 2</a>
<a href="#subtitle-1">Post subtitle 1</a>
<a href="#subtitle-2">Post subtitle 2</a>
<a href="#subtitle-3">Post subtitle 3</a>
<a href="#subtitle-4">Post subtitle 4</a>
The expect results:
<h2 id="title-1">Post title 1</h2>
<h3 id="subtitle-1">Post subtitle 1</h3>
<h3 id="subtitle-2">Post subtitle 2</h3>
<h2 id="title-2">Post title 2</h2>
<h3 id="subtitle-3">Post subtitle 3</h3>
<h3 id="subtitle-4">Post subtitle 4</h3>
<a href="#title-1">Post title 1</a>
<a href="#subtitle-1">Post subtitle 1</a>
<a href="#subtitle-2">Post subtitle 2</a>
<a href="#title-2">Post title 2</a>
<a href="#subtitle-3">Post subtitle 3</a>
<a href="#subtitle-4">Post subtitle 4</a>
I don't know how I can get all H3 between two H2 so any help could be helpful.