I want to generate a kind toc for a html document with jQuery – without
using any plugins. I’m just starting to learn/improve my jQuery know-how.
HTML input:
<div id="toc"></div>
<h3><a name="construction-block"></a>Construction Block</h3><p>...</p>
<h3><a name="construction-box"></a>Construction Box</h3><p>...</p>
...
JS:
$(document).ready(function(){
$("#toc").append('<p>table of contents:</p>');
$("h3").each(function(i) {
var current = $(this);
$("#toc").append("<h3>"+current.html()+"</h3>");
});
})
HTML output
<div id="toc">
<p>table of contents:</p>
<h3>
<a name="construction-block"></a>
Construction Block
</h3>
<h3>
<a name="construction-box"></a>
Construction Boxk
</h3>
</div>
It’s only partial success.
Desired HTML output
<div id="toc">
<p>table of contents:</p>
<h3>
<a href="#construction-block">Construction Block</a>
</h3>
<h3>
<a href="#construction-box">Construction Box</a>
</h3>
</div>
I’d suggest the following (given some changes in the HTML):
This jQuery creates an ordered list (which is, essentially, a semantic definition of what a table of contents is), and appends the text of the
h3elements to a newaelement within newly-created, and appended, list-items.The HTML changes are the removal of the
<a>elements, since theidcan (and should) be used instead of named anchors (and this also works in IE).The new HTML:
JS Fiddle demo.
I didn’t think of this until now, but you could achieve the same even without
idattributes on theh3elements, and simply use the jQuery to create the relevantidattributes as it goes:JS Fiddle demo.
References:
append().appendTo().String.replace().String.toLowerCase().text().